用于“谷歌以图搜图”的Python脚本
我查了一下谷歌搜索的API,发现他们并没有发布可以用来搜索“图片”的API。所以,我在想有没有什么Python脚本或者库,可以让我自动化实现“通过图片搜索”的功能。
3 个回答
-1
你可以试试这个链接:https://developers.google.com/image-search/v1/jsondevguide#json_snippets_python。虽然这个内容已经不再更新了,但看起来还是能用。
3
这件事让我觉得挺烦的,所以我想在搜索“脚本谷歌图片搜索”时,看到的第一个与Python有关的StackOverflow帖子上留个评论。最让人烦的是在谷歌的网页界面上设置你的应用程序和自定义搜索引擎(CSE)。不过,一旦你拿到你的API密钥和CSE,就可以在你的环境中定义它们,然后做一些像下面这样的事情:
#!/usr/bin/env python
# save top 10 google image search results to current directory
# https://developers.google.com/custom-search/json-api/v1/using_rest
import requests
import os
import sys
import re
import shutil
url = 'https://www.googleapis.com/customsearch/v1?key={}&cx={}&searchType=image&q={}'
apiKey = os.environ['GOOGLE_IMAGE_APIKEY']
cx = os.environ['GOOGLE_CSE_ID']
q = sys.argv[1]
i = 1
for result in requests.get(url.format(apiKey, cx, q)).json()['items']:
link = result['link']
image = requests.get(link, stream=True)
if image.status_code == 200:
m = re.search(r'[^\.]+$', link)
filename = './{}-{}.{}'.format(q, i, m.group())
with open(filename, 'wb') as f:
image.raw.decode_content = True
shutil.copyfileobj(image.raw, f)
i += 1