Python and selenium image limit and download directory

I am trying to automatically download some images through selenium’s click functionality and I am using a chrome webdriver and python as the programming language.

How can I limit the number of images downloaded (ex. I want to download only 120 images through google search but my code downloads all images on the page)

How can I select the download directory through the python program so that it does not get downloaded in the default Downloads directory.

below is my codes

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import urllib.request

driver = webdriver.Chrome()
elem = driver.find_element_by_name(“q”)


Get scroll height

last_height = driver.execute_script(“return document.body.scrollHeight”)

while True:
# Scroll down to bottom
driver.execute_script(“window.scrollTo(0, document.body.scrollHeight);”)

# Wait to load page

# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
last_height = new_height

images = driver.find_elements_by_css_selector(".rg_i.Q4LuWd")
count = 1
for image in images:
imgUrl = driver.find_element_by_xpath("/html/body/div[2]/c-wiz/div[3]/div[1]/div/div/div/div/div[1]/div[1]/div[3]/a[1]/div[1]/img").get_attribute(“src”)
urllib.request.urlretrieve(imgUrl, str(count) + “test.jpg”)
count = count + 1

driver.close()Preformatted text

You can use the enumerate() function when iterating over the images to get an index, and break from the loop when it crosses some limit. That could also replace the count variable you currently have.

limit = 120
for i, image in enumerate(images):
    if i >= limit:
    # do the download stuff here

By default i will start from zero, the documentation describes how to change that if you want to start from 1 as with the count.

When posting code in the future, please enclose it all in a Markdown code block (with triple backticks ``` as beginning and end). It’s much easier to read that way, which also makes it more likely people can help you.

I am so sorry about seeing your reply late. I discovered the notification now. Anyway, your reply helped me a lot! Thank you so much!

1 Like