__author__ = 'omriko'
from selenium import webdriver
import urllib
import urlparse

def get_similar_images_urls(browser, image_url):
    # prepare image url
    google_image_search_url= "https://www.google.co.il/searchbyimage?hl=en-IL&image_url="
    image_url_encoded = urllib.quote_plus(image_url)
    image_search_url= google_image_search_url + image_url_encoded

    # open google base search
    browser.get(image_search_url)

    # click on the "Visually similar images"
    browser.find_element_by_link_text('Visually similar images').click()

    # get results list
    results = browser.find_elements_by_css_selector(".rg_di.rg_el.ivg-i a")

    links = []

    # iterate results
    for result in results:
        # get link from result object
        link = result.get_attribute('href')

        # link will be in the format: http://www.google.co.il/imgres?imgurl=...&imgrefurl=...&h=...&w=...&tbnid=...&docid=...&hl=...&ei=...&tbm=...
        # we only need imagefurl, lets fetch it
        parsed_link = urlparse.urlparse(link)
        page_link = urlparse.parse_qs(parsed_link.query)['imgrefurl']

        links.append(page_link)

    return links

# open browser in URL
browser = webdriver.Firefox()

# fetch links
links = get_similar_images_urls(browser, image_url)