Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Downloads a random wallpaper based on preset search terms using Google API. Read tutorial of how to install it here:
from urllib import urlencode
from urllib2 import urlopen
import re
import json
from pprint import pprint
from random import randint
from os import remove, path
from time import sleep
from glob import glob
wallpaper_dir = '/path/to/wallpaper/dir'
minimum_width = 1366
minimum_height = 768
image_searches = (
'cherry blossoms',
#optional 2nd terms
'wide angle',
#optional 3rd terms
def random_item_from_list(list):
return list[ randint(0, len(list) - 1) ]
random_image_search = random_item_from_list(image_searches)
def get_random_image_url():
search_term = ''
for set_of_terms in random_image_search:
term = random_item_from_list(set_of_terms)
search_term = search_term + ' ' + term
search_term = search_term.strip()
print search_term
#start = randint(0,90)
#print 'Starting on page ' + str(start)
search_query = urlencode(dict(
key = api_key,
cx = engine_id,
searchType = 'image',
imgType = 'photo',
#safe = 'high',
#imgSize = 'xxlarge', # icon, small, medium, large, xlarge, xxlarge, huge
#start = start,
q = search_term + ' wallpaper'
search_url = '' % search_query
results = json.loads(urlopen(search_url).read())['items']
for i in xrange(0,10):
result = random_item_from_list(results)
if not result['image']['width'] < minimum_width and not result['image']['height'] < minimum_height:
print 'Width or height not enough, selecting another...'
return result['link']
for i in xrange(0,10):
image_url = get_random_image_url()
response = urlopen(image_url)
header ='Content-Type')
print header
if not re.match('image','Content-Type')):
raise BaseException('ERROR: Image hotlinking protected.')
response =
with open(path.join(wallpaper_dir, path.basename(image_url)), 'wb') as file:
with open(path.join(wallpaper_dir, 'wallpaper.jpg'), 'wb') as file:
except BaseException as e:
print e
print 'Retrying...'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.