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

14

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

不幸的是,Google没有为此提供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()

如果您是商业用户,TinEye是一个不错的选择。如果您可以将图片上传到某个地方,那么使用网址www.google.com/searchbyimage?image_url=IMAGE_URL会很有用。 - Others
1个回答

21

如果您乐意安装请求模块,这很容易实现。反向图像搜索工作流程目前包括一个带有多部分正文的单个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 可能随时决定更改此工作流程!


1
在这个示例代码中漏掉的一个附加项是:import webbrowser - David Metcalfe
2
上面答案中返回的 fetchUrl 实际上是通过模糊匹配生成的图像指纹。 - Tengerye
@Uri Zarfaty,这很明显,但您忘记了import webbrowser - Ghoul Fool
请问您能详细说明如何找到第一个K个相似的图像吗? - Peter
嘿,@Peter,如果你懂scrapy甚至是CSS_Selector或XPATH,那么你可以很容易地找到它。 - Muhammad Afzaal
1
目前这个功能无法使用,已经尝试过了,谷歌显示“图像搜索目前无法使用”。 - zicameau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接