AKG*_*AKG 8 python automation google-image-search
我检查了Google Search API,似乎他们还没有发布任何用于搜索"图片"的API.所以,我想知道是否存在一个python脚本/库,我可以通过它自动执行"按图搜索功能".
这很烦人,我想我应该对第一个与 python 相关的 stackoverflow 结果“脚本谷歌图像搜索”发表评论。其中最烦人的部分是在 Google 的 Web UI 中设置正确的应用程序和自定义搜索引擎 (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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4204 次 |
| 最近记录: |