Skip to content

Instantly share code, notes, and snippets.

Created May 27, 2012 22:52
Show Gist options
  • Save crizCraig/2816295 to your computer and use it in GitHub Desktop.
Save crizCraig/2816295 to your computer and use it in GitHub Desktop.
Download images from Google Image search using Python
import json
import os
import time
import requests
from PIL import Image
from StringIO import StringIO
from requests.exceptions import ConnectionError
def go(query, path):
"""Download full size images from Google image search.
Don't print or republish images without permission.
I used this to train a learning algorithm.
BASE_URL = ''\
'v=1.0&q=' + query + '&start=%d'
BASE_PATH = os.path.join(path, query)
if not os.path.exists(BASE_PATH):
start = 0 # Google's start query string parameter for pagination.
while start < 60: # Google will only return a max of 56 results.
r = requests.get(BASE_URL % start)
for image_info in json.loads(r.text)['responseData']['results']:
url = image_info['unescapedUrl']
image_r = requests.get(url)
except ConnectionError, e:
print 'could not download %s' % url
# Remove file-system path characters from name.
title = image_info['titleNoFormatting'].replace('/', '').replace('\\', '')
file = open(os.path.join(BASE_PATH, '%s.jpg') % title, 'w')
try:, 'JPEG')
except IOError, e:
# Throw away some gifs...blegh.
print 'could not save %s' % url
print start
start += 4 # 4 images per page.
# Be nice to Google and they'll be nice back :)
# Example use
go('landscape', 'myDirectory')
Copy link

ghost commented Dec 25, 2018

bah ca a pas tout mis:
en gros pour les # tu met un try except pour ignorer l'erreur !

Copy link

The API is no longer available unfortunately.

TypeError: 'NoneType' object is not subscriptable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment