11

我有一个应用程序,它基本上是存储在本地驱动器上的图像数据库。有时我需要找到更高分辨率的版本或图像的网络源,而谷歌的反向图像搜索非常适合。

不幸的是,谷歌没有它的 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()
4

1 回答 1

18

如果您乐于安装requests 模块,这很容易做到。反向图像搜索工作流当前由一个 POST 请求组成,该请求具有多部分正文到上传 URL,其响应是对实际结果页面的重定向。

import requests
import webbrowser

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 可能随时决定更改此工作流程!

于 2015-03-01T11:22:37.900 回答