Search code examples
pythonjsonapigoogle-apigoogle-custom-search

Google Search by Image in Python


Is there a way to use the Google search by Image feature in Python? I was considering taking an image file from a specified location and using that file to get relevant search results. I have looked through the Google Custom Search API and cannot seem to find anything on this topic. Any help would be appreciated.


Solution

  • The following code snippet shows how to make a request to the Google Image Search API using Python. This sample assumes Python 2.4 or higher. You may need to download and install simplejson.

    import urllib2
    import simplejson
    
    url = ('https://ajax.googleapis.com/ajax/services/search/images?' +
           'v=1.0&q=barack%20obama&userip=INSERT-USER-IP')
    
    request = urllib2.Request(url, None, {'Referer': /* Enter the URL of your site here */})
    response = urllib2.urlopen(request)
    
    # Process the JSON string.
    results = simplejson.load(response)
    # now have some fun with the results...