8

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

4

3 回答 3

3

没有可用的 API,但您可以解析页面并模仿浏览器,但我不知道您需要解析多少数据,因为 google 可能会限制或阻止访问。

您可以通过简单地使用 urllib 并设置正确的标头来模仿浏览器,但是如果您认为从 python 解析复杂的网页可能很困难,您可以直接使用无头浏览器,如phontomjs,在浏览器中使用获取正确的元素是微不足道的javascript/DOM

在尝试所有这些之前请注意检查谷歌的TOS

于 2011-12-02T21:15:02.797 回答
3

这很烦人,以至于我想我会对“脚本谷歌图像搜索”的第一个与 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
于 2016-02-24T20:22:49.927 回答
-1

你可以试试这个: https ://developers.google.com/image-search/v1/jsondevguide#json_snippets_python 它已被弃用,但似乎有效。

于 2012-10-31T15:32:39.957 回答