Skip to content

Instantly share code, notes, and snippets.

@g0053
Forked from grifball/fetch_google_image.py
Created December 3, 2020 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g0053/58911adee9846260ec2cde3f0d67553c to your computer and use it in GitHub Desktop.
Save g0053/58911adee9846260ec2cde3f0d67553c to your computer and use it in GitHub Desktop.
Download a random picture from Google image search.
#!/usr/bin/env python
# coding: utf-8
# Download a random picture from Google image search.
#
# Usage:
# $ fetch_google_image.py cat cute # Download a cute cat picture
import os
import sys
import urllib
import urllib2
import json
import random
import imghdr
apiKey='' # put your API key here
searchEngine='' # you also have to generate a search engine token
if len(sys.argv) <= 1:
print('Usage:')
print('python fetch_google_image.py cat cute')
exit()
q = ''
for arg in sys.argv[1:]:
q += urllib.quote(arg) + '+'
f = urllib2.urlopen('https://www.googleapis.com/customsearch/v1?key='+apiKey+'&cx='+searchEngine+'&q='+q+'&searchType=image')
data = json.load(f)
f.close()
results = data['items']
url = results[random.randint(0, len(results) - 1)]['link']
urllib.urlretrieve(url, './image')
imagetype = imghdr.what('./image')
if not(type(imagetype) is None):
os.rename('./image', './image.' + imagetype)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment