DEV Community

loading...

Python: Get and Save Google images with Selenium

rickavmaniac profile image rickavmaniac ・1 min read

I create a small Python code to get and save images from Google images.

from selenium import webdriver
import time, requests

def search_google(search_query):
    browser = webdriver.Chrome()
    search_url = f"https://www.google.com/search?site=&tbm=isch&source=hp&biw=1873&bih=990&q={search_query}"
    images_url = []

    # open browser and begin search
    browser.get(search_url)
    elements = browser.find_elements_by_class_name('rg_i')

    count = 0
    for e in elements:
        # get images source url
        e.click()
        time.sleep(1)
        element = browser.find_elements_by_class_name('v4dQwb')

        # Google image web site logic
        if count == 0:
            big_img = element[0].find_element_by_class_name('n3VNCb')
        else:
           big_img = element[1].find_element_by_class_name('n3VNCb')

        images_url.append(big_img.get_attribute("src"))

        # write image to file
        reponse = requests.get(images_url[count])
        if reponse.status_code == 200:
            with open(f"search{count+1}.jpg","wb") as file:
                file.write(reponse.content)

        count += 1

        # Stop get and save after 5
        if count == 5:
            break

    return images_url

items = search_google('dog')

Alt Text

Discussion (1)

pic
Editor guide
Collapse
rahul523680 profile image
rahul kumar

Hi,

This a very nice post that would help me in my research. Can you please help me in changing this code to download products image from google.
I have a list of products name, I need to download products images from google(or any search engine) and store it to a folder(any). I tried with the help of stack but it is giving me error. I tried:
from google_images_download import google_images_download

response = google_images_download.googleimagesdownload()
arguments = {"keywords":"Polar bears,baloons,Beaches","limit":20,"print_urls":True}

paths = response.download(arguments)
print(paths)

which is giving me the folders only and not image. All photos can be stored in one folder too.