Python Selenium with Chrome, how to download to a specified folder with specified file name

  • 8 months ago
Comment

ChatGPT
1 / 1

To download files using Selenium with Chrome WebDriver and specify the download folder and file name, you need to use Chrome options to set preferences. Here's how you can do it:

python
from selenium import webdriver

# Set your desired download path and file name
download_path = "C:\\Path\\to\\your\\download\\folder"
file_name = "downloaded_file.txt"

# Configure Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-notifications") # Disable notifications
chrome_options.add_argument("--disable-popup-blocking") # Disable popup blocking

# Set download preferences
prefs = {"download.default_directory": download_path}
chrome_options.add_experimental_option("prefs", prefs)

# Initialize Chrome WebDriver with options
driver = webdriver.Chrome(executable_path="path_to_chromedriver.exe", options=chrome_options)

# Open a URL that triggers a download
driver.get("https://example.com/download_link")

# Wait for the download to complete (You may need to customize this)
# For example, using WebDriverWait with expected_conditions to check for the downloaded file
# Make sure you import necessary classes from selenium.webdriver.support module

# After the download is complete, verify if the downloaded file exists
import os
downloaded_file_path = os.path.join(download_path, file_name)
if os.path.exists(downloaded_file_path):
print("Downloaded file exists at:", downloaded_file_path)
else:
print("Downloaded file not found!")

# Close the WebDriver
driver.quit()

In this example, we're using Chrome options to set preferences related to downloads. The download.default_directory preference specifies the folder where the downloads should be saved.

Note that you might need to adjust the waiting logic after initiating the download, as the exact behavior can vary depending on the website and the download process. Using WebDriverWait with expected_conditions to check for the presence of the downloaded file is a common approach.

Make sure to replace "path_to_chromedriver.exe" with the actual path to your ChromeDriver executable and "https://example.com/download_link" with the URL that triggers the download.