Google Image Search

And How To Use Python to automate it!

image-search-google
Step 1 – install Google-Images-Search
instructions-google
Step 2 – follow the installation instructions
env variables
Step 3 – set up the .env file with the API key and CX code you got when you generated your API credentials with Google.
Note : Make sure you enabled image search by setting it to “on”

code:

from google_images_search import GoogleImagesSearch
from dotenv import load_dotenv
import os
# load the API key and CX code from .env file
load_dotenv()

# create an 'ims' sub directory if it doesn't already exists
if not os.path.exists('ims/'):
  os.mkdir('ims/')
pathz = 'ims/'
# Get env variables
DK = os.environ.get('DEVELOPER_KEY')
CX = os.environ.get('CX')

# custom progressbar function
def my_progressbar(url, progress):
    print(url + " " + progress + "%")

# create google images search - object
gis = GoogleImagesSearch(DK, CX, progressbar_fn=my_progressbar)
# using contextual mode (Curses)
with GoogleImagesSearch(DK, CX) as gis:
    # define search params:
    _search_params = {"q": "tree", 
        "num": 3, 
        "safe": "off", 
        "fileType": "png"
        }
    gis.search(search_params=_search_params, path_to_dir=pathz)

print("\nDone\n")
3 images of trees – here is one of them!

Limit Exceeded!

If you see “Error 429 when requesting…” or…

RESOURCE_EXHAUSTED

then you may have exceeded your daily allowance for API calls. So be careful when testing the code not to make too many requests.

quota-reached-google-api
Quota reached!

To install our code you can use pip:

pip install gimdl

https://pypi.org/project/gimdl/

Next article

Creating a Python Package