【发布时间】:2016-02-06 14:28:59
【问题描述】:
我正在尝试找到一种有效且可复制的方法来从 Google 图片搜索中批量下载全尺寸图片文件。其他人也问过类似的问题,但我没有找到任何我正在寻找或我理解的东西。
大多数是指已弃用的 Google Image Search API 或 Google Custom Search API,它们似乎不适用于整个网络,或者只是从单个 URL 下载图像。
我想这可能是一个两步过程:首先,从搜索中提取所有图像 URL,然后从中批量下载?
我应该补充一点,我是一个初学者(这可能很明显;抱歉)。因此,如果有人可以解释并指出我正确的方向,那将不胜感激。
我还研究了免费软件选项,但这些选项似乎也参差不齐。除非有人知道可靠的。
Download images from google image search (python)
如果有人知道这些标签的任何信息,以及它们是否存在于某处/与图像相关联? https://en.wikipedia.org/wiki/Google_Image_Labeler
import json
import os
import time
import requests
from PIL import Image
from StringIO import StringIO
from requests.exceptions import ConnectionError
def go(query, path):
"""Download full size images from Google image search.
Don't print or republish images without permission.
I used this to train a learning algorithm.
"""
BASE_URL = 'https://ajax.googleapis.com/ajax/services/search/images?'\
'v=1.0&q=' + query + '&start=%d'
BASE_PATH = os.path.join(path, query)
if not os.path.exists(BASE_PATH):
os.makedirs(BASE_PATH)
start = 0 # Google's start query string parameter for pagination.
while start < 60: # Google will only return a max of 56 results.
r = requests.get(BASE_URL % start)
for image_info in json.loads(r.text)['responseData']['results']:
url = image_info['unescapedUrl']
try:
image_r = requests.get(url)
except ConnectionError, e:
print 'could not download %s' % url
continue
# Remove file-system path characters from name.
title = image_info['titleNoFormatting'].replace('/', '').replace('\\', '')
file = open(os.path.join(BASE_PATH, '%s.jpg') % title, 'w')
try:
Image.open(StringIO(image_r.content)).save(file, 'JPEG')
except IOError, e:
# Throw away some gifs...blegh.
print 'could not save %s' % url
continue
finally:
file.close()
print start
start += 4 # 4 images per page.
# Be nice to Google and they'll be nice back :)
time.sleep(1.5)
# Example use
go('landscape', 'myDirectory')
更新
我能够使用here 指定的完整网络创建自定义搜索,并成功执行以获取图片链接,但正如上一篇文章中提到的,它们与正常的 Google 图片不完全一致结果。
【问题讨论】:
-
这似乎是一个与 python 相关的问题,而不是关于批处理文件。我会为您更新标签,但我建议您阅读您使用的标签的信息页面。
-
谢谢@DennisvanGils
-
如果您正在寻找您自己的应用程序的结果与您的常规 Google 图片搜索不同的原因,那是因为 Google 会根据您的 cookie 等更改结果,而您的应用程序没有这些
-
@DennisvanGils 更多关于更新的旁注。但是谢谢,我想它是那样的。如前所述,我需要的主要内容是能够有效地从每个图像链接下载图像,并尽可能使用相关的 alt 标签。
-
不确定您是否仍在尝试完成这项工作。但是,Google 不仅会关心您的 cookie,还会关心您的用户代理字符串。抓取 Google 也不是一件容易的事,因为他们认为这违反了他们的条款和条件,如果他们发现抓取内容会迅速阻止您。
标签: python image batch-processing google-custom-search google-image-search