Search code examples
pythonautomationgoogle-image-search

Python script for "Google search by image"


I have checked Google Search API's and it seems that they have not released any API for searching "Images". So, I was wondering if there exists a python script/library through which I can automate the "search by image feature".


Solution

  • This was annoying enough to figure out that I thought I'd throw a comment on the first python-related stackoverflow result for "script google image search". The most annoying part of all this is setting up your proper application and custom search engine (CSE) in Google's web UI, but once you have your api key and CSE, define them in your environment and do something like:

    #!/usr/bin/env python
    
    # save top 10 google image search results to current directory
    # https://developers.google.com/custom-search/json-api/v1/using_rest
    
    import requests
    import os
    import sys
    import re
    import shutil
    
    url = 'https://www.googleapis.com/customsearch/v1?key={}&cx={}&searchType=image&q={}'
    apiKey = os.environ['GOOGLE_IMAGE_APIKEY']
    cx = os.environ['GOOGLE_CSE_ID']
    q = sys.argv[1]
    
    i = 1
    for result in requests.get(url.format(apiKey, cx, q)).json()['items']:
      link = result['link']
      image = requests.get(link, stream=True)
      if image.status_code == 200:
        m = re.search(r'[^\.]+$', link)
        filename = './{}-{}.{}'.format(q, i, m.group())
        with open(filename, 'wb') as f:
          image.raw.decode_content = True
          shutil.copyfileobj(image.raw, f)
        i += 1