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()
driver.get(“https://www.google.co.kr/imghp?hl=ko&tab=ri&authuser=0&ogbl”)
elem = driver.find_element_by_name(“q”)
elem.send_keys(“apple”)
elem.send_keys(Keys.RETURN)

SCROLL_PAUSE_TIME = 1

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
time.sleep(SCROLL_PAUSE_TIME)

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

images = driver.find_elements_by_css_selector(".rg_i.Q4LuWd")
count = 1
for image in images:
try:
image.click()
time.sleep(2)
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
except:
pass

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:
        break
    # 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.