import os, sys
import time
from urllib import FancyURLopener
import urllib2
import json
import random
from IPython.core.display import Image
class MyOpener(FancyURLopener):
version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
def find_beer_images(search_term,myopener,beer_count=50):
'''Beer images generator'''
count = 0
search_term = search_term.replace(' ','%20')
for beer in range(1, beer_count):
url = 'https://ajax.googleapis.com/ajax/services/search/images?{}{}&start={}&userip=MyIP&imgsz=large'.\
format('v=1.0&q=',search_term, random.sample(range(60),1)[0])
#print url
request = urllib2.Request(url, None, {'Referer': 'testing'})
response = urllib2.urlopen(request)
results = json.load(response)
data = results['responseData']
try:
data_info = data['results']
except:
pass
for myUrl in data_info:
count = count + 1
yield myUrl['unescapedUrl']
myopener.retrieve(myUrl['unescapedUrl'],str(count)+'.jpg')
def collect_images(beer_images,number_of_beer):
beer_lst = []
for number,image in enumerate(beer_images,1):
beer_lst.append(image)
if number == number_of_beer:
return beer_lst
def bottel_text(beer_lst,number_of_beer):
for beer_count in range(number_of_beer-1, 0, -1):
if beer_count > 1:
print "{0} bottles of beer on the wall {0} bottles of beer.".format(beer_count)
print '---'
beer_lst.pop()
for img in beer_lst:
try:
image = Image(img)
display(image)
except:
pass
if beer_count > 2:
beer_text = str(beer_count - 1) + " bottles of beer on the wall."
beer_text = "{} bottles of beer on the wall.".format(beer_count - 1)
else:
beer_text = "1 bottle of beer on the wall."
elif beer_count == 1:
print "1 bottle of beer on the wall, 1 bottle of beer."
image = Image(beer_lst[-1])
display(image)
beer_text = "no more beer on the wall!"
print '---'
print "Take one down, pass it around,", beer_text
if __name__ == '__main__':
myopener = MyOpener()
search_term = "beer"
number_of_beer = 6
beer_images = find_beer_images(search_term,myopener)
beer_lst = collect_images(beer_images,number_of_beer) #beer lst
bottel_text(beer_lst,number_of_beer)
5 bottles of beer on the wall 5 bottles of beer. ---
--- Take one down, pass it around, 4 bottles of beer on the wall. 4 bottles of beer on the wall 4 bottles of beer. ---
--- Take one down, pass it around, 3 bottles of beer on the wall. 3 bottles of beer on the wall 3 bottles of beer. ---
--- Take one down, pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall 2 bottles of beer. ---
--- Take one down, pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer.
--- Take one down, pass it around, no more beer on the wall!