*! !! This Google Image API is no longer available! !!
python
sudo pip install httplib2
get_imgs.py
#-*- coding:utf-8 -*-
import json
import os
import urllib2
import httplib2
import shutil
# search_Search for word image links
def get_img_urls(search_word, n):
    img_url=[]
    images_per_request=8
    # https://developers.google.com/image-search/v1/jsondevguide
    url = "http://ajax.googleapis.com/ajax/services/search/images?q={0}&v=1.0&imgsz=huge&rsz="+str(images_per_request)+"&start={1}"
    urlencoded = urllib2.quote(search_word)
    # search_Get n image URLs that match word
    for i in range(n):
        res = urllib2.urlopen(url.format(urlencoded, i*images_per_request))
        data = json.load(res)
        img_url += [result["url"] for result in data["responseData"]["results"]]
    return img_url
#Save the image file at the URL
def url_download(search_word,urls):
    if os.path.exists(search_word)==False:
        os.mkdir(search_word)
    opener = urllib2.build_opener()
    http = httplib2.Http(".cache")
    #Image DL for the number of URLs
    for i in range(len(set(urls))):
        try:
            fn, ext = os.path.splitext(urls[i])
            response, content = http.request(urls[i])
            with open(str(i)+ext, 'wb') as f:
                f.write(content)
            shutil.move((str(i)+ext).encode("utf-8"), search_word)
        except:
            continue
#It failed when n was 10. 8 is ok
def main(search_word, n):
    urls = get_img_urls(search_word, n)
    url_download(search_word,urls)
if __name__ == '__main__':
    main("Puppy chihuahua", 2)
    main("Chihuahua sitting", 2)
Recommended Posts