-
-
Save g0053/58911adee9846260ec2cde3f0d67553c to your computer and use it in GitHub Desktop.
Download a random picture from Google image search.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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