Skip to content

Instantly share code, notes, and snippets.

@macedd
Created July 5, 2015 01:16
Show Gist options
  • Save macedd/61fe1f806bf3cf030a22 to your computer and use it in GitHub Desktop.
Save macedd/61fe1f806bf3cf030a22 to your computer and use it in GitHub Desktop.
Python Class: Google Image Search Api
import urllib2, urllib
import simplejson
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
class ImageApi(object):
uri = "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&%s"
params = { 'q': 'term', 'imgsz': 'medium|large|xlarge', 'start': 0, 'imgtype': 'photo' }
# result keys
keys = ['titleNoFormatting', 'originalContextUrl', 'height', 'width', 'unescapedUrl']
def search(self, query='', params={}):
queryParams = dict(self.params)
queryParams.update({'q':query})
queryParams.update(params)
queryUri = self.uri % (urllib.urlencode(queryParams), )
# load api query
f = opener.open(queryUri)
res = simplejson.load(f)
return self.load(res)
def load(self, response):
images = []
for image in response['responseData']['results']:
# filter keys
image = {k: v for k, v in image.items() if k in self.keys}
images.append(image)
return images
def download(self, count=0):
pass
images = ImageApi()
images.search('Barak Obama')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment