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

妖精的绣舞 提交于 2019-12-13 06:18:13

问题


Is there a way I can download all/some the image files (e.g. JPG/PNG) from a Google Images search result?

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:

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 (e.g. JPG/PNG) from my own search result from Google Images without necessarily having a list of the image urls beforehand.

P.S.

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.


回答1:


You can use the Google API like this, where BLUE and DOG are your search parameters:

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

You need to parse this JSON format before you can use the links directly.

Here's a start to your JSON parsing:

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


来源:https://stackoverflow.com/questions/32035973/in-python-is-there-a-way-i-can-download-all-some-the-image-files-e-g-jpg-png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!