使用 Python 在 Yandex Images 中反向搜索图像

Reverse search an image in Yandex Images using Python

我对自动化反向图像搜索很感兴趣。 Yandex 尤其适用于打击鲶鱼,甚至比 Google 图片更好。所以,考虑这个 Python 代码:

import requests
import webbrowser

try:
    filePath = "C:\path\whateverThisIs.png"
    searchUrl = 'https://yandex.ru/images/'
    multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
    response = requests.post(searchUrl, files=multipart, allow_redirects=False)
    #fetchUrl = response.headers['Location']
    print(response)
    print(dir(response))
    print(response.content)
    input()
except Exception as e:
    print(e)
    print(e.with_traceback)
    input()```

脚本因 KeyError 失败,未找到 'location'。我知道代码有效,因为如果您将 searchUrl 替换为 http://www.google.hr/searchbyimage/upload,那么脚本 returns 将是正确的 url。 因此,简而言之,预期结果将是带有图像搜索的 url。实际上,我们在本应存储 url 的地方得到了一个 KeyError。 显然,Yandex 的工作方式并不完全相同,也许 url 已关闭(尽管我尝试了很多变体)或者原因可能完全不同。

无论如何,非常感谢帮助解决这个问题!

开发人员没有 API。您可以尝试从您的浏览器反向 inginer 查询,但您将不得不处理 anty robot protect。

另一种加快进程的方法(但仍然是手动的)

  1. 如此处所述 https://yandex.com/support/images/loaded-image.html 安装 Yandex.Browser 你有图像搜索的热键
  2. Host/make 您的站点的所有源图像都在搜索查询中
  3. 在 Yandex.Browser 中打开您的网站使用 "right mouse click"+"搜索图片 yandex
  4. 从带有结果的页面复制您需要的内容

您可以使用此代码通过图片搜索获得 url。在 ubuntu 18.04 上测试,使用 python 3.7 和请求 2.23.0

import json

import requests

file_path = "C:\path\whateverThisIs.png"
search_url = 'https://yandex.ru/images/search'
files = {'upfile': ('blob', open(file_path, 'rb'), 'image/jpeg')}
params = {'rpt': 'imageview', 'format': 'json', 'request': '{"blocks":[{"block":"b-page_type_search-by-image__link"}]}'}
response = requests.post(search_url, params=params, files=files)
query_string = json.loads(response.content)['blocks'][0]['params']['url']
img_search_url = search_url + '?' + query_string
print(img_search_url)