-->

In Python, is there a way I can download all/some

2019-09-07 01:34发布

问题:

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'])