Created
July 5, 2015 01:16
-
-
Save macedd/61fe1f806bf3cf030a22 to your computer and use it in GitHub Desktop.
Python Class: Google Image Search Api
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
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