使用POST请求进行Google反向图片搜索

时间:2014-04-24 13:20:49

标签: python post google-image-search

我有一个应用程序,它基本上是存储在我本地驱动器上的图像数据库。有时我需要找到更高分辨率的版本或图片的网络来源,而Google的reverse image search则非常适合。

不幸的是,谷歌没有它的API,所以我不得不想办法手动完成它。现在我正在使用Selenium,但这显然有很多开销。我想要一个简单的解决方案,使用urllib2或类似的东西 - 发送POST请求,获取搜索URL,然后我可以将该URL传递给webbrowser.open(url)以在我已经打开的系统浏览器中加载它。

这就是我现在正在使用的内容:

gotUrl = QtCore.pyqtSignal(str)
filePath = "/mnt/Images/test.png"

browser = webdriver.Firefox()
browser.get('http://www.google.hr/imghp')

# Click "Search by image" icon
elem = browser.find_element_by_class_name('gsst_a')
elem.click()

# Switch from "Paste image URL" to "Upload an image"
browser.execute_script("google.qb.ti(true);return false")

# Set the path of the local file and submit
elem = browser.find_element_by_id("qbfile")
elem.send_keys(filePath)

# Get the resulting URL and make sure it's displayed in English
browser.get(browser.current_url+"&hl=en")
try:
    # If there are multiple image sizes, we want the URL for the "All sizes" page
    elem = browser.find_element_by_link_text("All sizes")
    elem.click()
    gotUrl.emit(browser.current_url)
except:
    gotUrl.emit(browser.current_url)
browser.quit()

1 个答案:

答案 0 :(得分:12)

如果您愿意安装requests module,这很容易做到。反向图像搜索工作流程当前包含一个POST请求,其中多部分正文到上传URL,其响应是重定向到实际结果页面。

import requests

filePath = '/mnt/Images/test.png'
searchUrl = 'http://www.google.hr/searchbyimage/upload'
multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
response = requests.post(searchUrl, files=multipart, allow_redirects=False)
fetchUrl = response.headers['Location']
webbrowser.open(fetchUrl)

当然,请记住Google可能决定随时更改此工作流程!