"Google search by image"的 Python 脚本

标签 python automation google-image-search

我已经检查了 Google 搜索 API,他们似乎还没有发布任何用于搜索“图片”的 API。所以,我想知道是否存在一个 python 脚本/库,通过它我可以自动执行“按图像搜索功能”。

最佳答案

这很烦人,我想我应该对“脚本谷歌图像搜索”的第一个 python 相关的 stackoverflow 结果发表评论。所有这一切中最烦人的部分是在 Google 的网络用户界面中设置适当的应用程序和自定义搜索引擎 (CSE),但是一旦您获得了 API key 和 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

关于 "Google search by image"的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8362386/

相关文章:

Python Pandas : Convert Rows as Column headers

ios - Instruments Automation 屏幕截图忽略以编程方式添加的控件

automation - 如何根据雪花中的任何文本文件自动创建表格?

PHP 在网站内按图像搜索

Python 3.6 在尝试导入 Tensorflow 时抛出错误

python - 处理扑克手牌时如何在python中使用类?

python - 如何检测Python Turtle图形中的X(关闭)按钮?

c# - 遍历 TabControl 中的 TabItems

iphone - 如何上传图片,然后在 iOS 中根据该图片执行自定义谷歌图片搜索?

PHP 按图像搜索 Google cURL 返回 302 已移动