简体   繁体   English

在Python中,有没有一种方法可以从** Google图片**搜索结果中下载全部/部分图片文件(例如JPG / PNG)?

[英]In Python, is there a way I can download all/some the image files (e.g. JPG/PNG) from a **Google Images** search result?

Is there a way I can download all/some the image files (eg JPG/PNG) from a Google Images search result? 有什么方法可以从Google图片搜索结果中下载全部/部分图片文件(例如JPG / PNG)?

I can use the following code to download one image that I already know its url: 我可以使用以下代码下载一个我已经知道其网址的图像:

import urllib.request
file = "Facts.jpg" # file to be written to
url = "http://www.compassion.com/Images/Hunger-Facts.jpg"
response = urllib.request.urlopen (url)
fh = open(file, "wb") #open the file for writing
fh.write(response.read()) # read from request while writing to file

To download multiple images, it has been suggested that I define a function and use that function to repeat the task for each image url that I would like to write to disk: 要下载多个图像,建议我定义一个函数,并使用该函数对要写入磁盘的每个图像url重复执行此任务:

def image_request(url, file):
response = urllib.request.urlopen(url)
fh = open(file, "wb") #open the file for writing
fh.write(response.read())

And then loop over a list of urls with: 然后使用以下命令遍历网址列表:

for i, url in enumerate(urllist):
image_request(url, str(i) + ".jpg")

However, what I really want to do is download all/some image files (eg JPG/PNG) from my own search result from Google Images without necessarily having a list of the image urls beforehand. 但是,我真正想做的是从我自己的搜索结果中从Google图像下载所有/某些图像文件(例如JPG / PNG),而不必事先获得图像网址列表。

PS 聚苯乙烯

Please I am a complete beginner and would favour an answer that breaks down the broad steps to achieve this over one that is bogs down on specific codes. 请我是一个完整的初学者,并且希望能得到一个答案,该答案将打破实现该目标的主要步骤,而不是使特定代码陷入困境的步骤。 Thanks. 谢谢。

You can use the Google API like this, where BLUE and DOG are your search parameters: 您可以像这样使用Google API,其中BLUE和DOG是您的搜索参数:

https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=BLUE%20DOG https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=BLUE%20DOG

There is a developer guide about this here: 这里有关于此的开发人员指南:

https://developers.google.com/image-search/v1/jsondevguide https://developers.google.com/image-search/v1/jsondevguide

You need to parse this JSON format before you can use the links directly. 您需要先解析此JSON格式,然后才能直接使用链接。

Here's a start to your JSON parsing: 这是JSON解析的开始:

import json
j = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print(j['two'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM