File download handling in Selenium Python - Build an Automation Script
import os import time import shutil from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options # Setup download directory DOWNLOAD_DIR = os.path.join(os.getcwd(), 'temp_download') if not os.path.exists(DOWNLOAD_DIR): os.makedirs(DOWNLOAD_DIR) # Configure Chrome options for file download chrome_options = Options() chrome_options.add_experimental_option('prefs', { 'download.default_directory': DOWNLOAD_DIR, 'download.prompt_for_download': False, 'download.directory_upgrade': True, 'safebrowsing.enabled': True }) # Initialize WebDriver service = Service() driver = webdriver.Chrome(service=service, options=chrome_options) try: driver.get('https://example.com/download') # Wait for the download link to be clickable wait = WebDriverWait(driver, 10) download_link = wait.until(EC.element_to_be_clickable((By.ID, 'download-file'))) # Click the download link download_link.click() # Wait for the file to appear in the download directory file_name = 'sample.pdf' file_path = os.path.join(DOWNLOAD_DIR, file_name) timeout = 20 # seconds poll_interval = 1 # second elapsed = 0 while elapsed < timeout: if os.path.exists(file_path): # Check if file is still being written (size stabilizes) initial_size = os.path.getsize(file_path) time.sleep(1) new_size = os.path.getsize(file_path) if initial_size == new_size and initial_size > 0: break time.sleep(poll_interval) elapsed += poll_interval # Assertion: file exists and is not empty assert os.path.exists(file_path), f"File {file_name} was not downloaded." assert os.path.getsize(file_path) > 0, f"File {file_name} is empty." finally: # Clean up: close browser and delete downloaded file and folder driver.quit() if os.path.exists(DOWNLOAD_DIR): shutil.rmtree(DOWNLOAD_DIR)
This script sets up a temporary download folder to keep downloads isolated and clean.
ChromeOptions are configured to automatically download files to this folder without prompts.
The script opens the target URL, waits explicitly for the download link to be clickable, then clicks it.
It then waits up to 20 seconds for the file to appear and ensures the file size stabilizes to confirm download completion.
Assertions check that the file exists and is not empty, ensuring the download succeeded.
Finally, the browser is closed and the temporary download folder is deleted to keep the environment clean.
Now add data-driven testing to download three different files with ids 'download-file1', 'download-file2', 'download-file3' and verify each file is downloaded correctly.