Save dog images from Google image search

*! !! This Google Image API is no longer available! !!

reference

Preparation

python


sudo pip install httplib2

code

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

Save dog images from Google image search
[Python] Download original images from Google Image Search
Scraping google search (image)
Get Google Image Search images in original size
Search and save images of Chino Kafu from Twitter
Image processing | predicting species from images
Get images by keyword search from Twitter
Image collection using Google Custom Search API
Image scraping ②-Get images from bing, yahoo, Flickr
[Selenium] If you can't scrape Google image search, crawl and collect thumbnail images alone.
[Latest] How to use Python library to save Google image search & use Chrome Driver on ubuntu
Get the image of "Suzu Hirose" by Google image search.
Detect lost search status from Google Chrome search query history
Extracted text from image
Collect large numbers of images using Bing's image search API
Image collection by calling Bing Image Search API v5 from Python