Downloading image to a specific directory using Selenium in Python

216 Views Asked by At

I need to download an image to a specific directory using Selenium in Python

Here is the following code:

import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
import pyautogui
from time import sleep

chrome_options = uc.ChromeOptions()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")

# Specify the download directory
prefs = {
    "download.default_directory": "C:/Users/ExampleUser/Documents/ExampleFolder/",
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": False
}
chrome_options.add_experimental_option("prefs", prefs)

# Create the webdriver instance with the modified options
driver = uc.Chrome(options=chrome_options)

#This is where I have used selenium to login to the website here
#havent posted the code to login

# Open the image page
driver.get('https://www.simplilearn.com/ice9/free_resources_article_thumb/what_is_image_Processing.jpg')
#This is just a random image, not the image on the website

sleep(3)

# Perform a right-click on the image
image_element = driver.find_element(By.XPATH, '/html/body/img')
sleep(3)
action_chains = ActionChains(driver)
action_chains.context_click(image_element).perform()
sleep(3)

# Press the "V" key to select the "Save Image As" option
pyautogui.press('v')

sleep(3)
# Press the Enter key to confirm the Save Image dialog
pyautogui.press('enter')

driver.quit()

It works if I do it on a random image as in the example above, but not when I am logged in then downloading an image from the website, it says Error Failed to download (it downloads from that website when I don't specify the directory).

1

There are 1 best solutions below

3
SIGHUP On

I have no idea why you're using selenium for this. You have a URL that takes you directly to the image. Therefore it's as simple as:

import requests
import os

TARGET_FILE = 'what_is_image_Processing.jpg'
TARGET_DIRECTORY = '/Volumes/G-Drive' # where you want to place the file
CHUNK = 64*1024 # some reasonable figure
URL = 'https://www.simplilearn.com/ice9/free_resources_article_thumb/{}'

with requests.get(URL.format(TARGET_FILE), stream=True) as response:
    response.raise_for_status()
    with open(os.path.join(TARGET_DIRECTORY, TARGET_FILE), 'wb') as image:
        for chunk in response.iter_content(CHUNK):
            image.write(chunk)