【发布时间】:2020-09-10 15:40:58
【问题描述】:
我对自动进行反向图像搜索很感兴趣。尤其是 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'。我知道代码有效,因为如果你用http://www.google.hr/searchbyimage/upload 替换searchUrl,那么脚本会返回正确的url。
因此,简而言之,预期的结果将是一个带有图像搜索的 url。实际上,我们在应该存储该 url 的位置得到一个 KeyError。
显然,Yandex 的工作方式并不完全相同,可能是网址已关闭(尽管我尝试了很多变体),或者原因可能完全不同。
无论如何,非常感谢帮助解决这个问题!
【问题讨论】:
-
您需要复制浏览器执行的 http 请求。使用浏览器的网络监视器查看发出的请求。正如您所指出的,它的工作方式与谷歌不同。它向带有许多参数的 URL 发出 POST 请求,例如返回 json 的
https://yandex.com/images/search?serpid=ntjh1wqE0ZzVt [...]。特别感兴趣的是键["blocks"][0]["params"]["url"],您将其值添加到基本 URL,从而生成类似于 yandex.com/images/… 的内容。这最终就是您想要的 URL。 -
您是否尝试了
HEAD或OPTIONS请求以查看他们的后端发生了什么(如果可以,请分享这些响应标头),或者也尝试'https://yandex.ru/images'而不是'https://yandex.ru/images/'?
标签: python parsing web-crawler yandex