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.
Practice
Solution
Step 1: Understand browser preferences role
Browser preferences let you control how downloads behave, like where files save.Step 2: Identify the correct purpose
Setting preferences to specify download folder avoids manual prompts and saves files automatically.Final Answer:
To specify the folder where downloaded files are saved automatically -> Option AQuick Check:
Download folder control = A [OK]
- Thinking preferences speed up browser loading
- Confusing download folder with browser theme
- Assuming preferences disable JavaScript
Solution
Step 1: Recall Firefox preference for download folder
The 'browser.download.folderList' preference expects an integer: 0 (desktop), 1 (default), 2 (custom folder).Step 2: Choose correct data type and value
Using integer 2 sets a custom folder; string or other types cause errors.Final Answer:
profile.set_preference('browser.download.folderList', 2) -> Option BQuick Check:
Integer 2 for custom folder = B [OK]
- Passing '2' as string instead of integer
- Using boolean True instead of integer
- Passing None which disables setting
import os
from selenium import webdriver
options = webdriver.FirefoxOptions()
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.dir', '/tmp/downloads')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/pdf')
driver = webdriver.Firefox(firefox_profile=profile, options=options)
driver.get('http://example.com/sample.pdf')
file_path = '/tmp/downloads/sample.pdf'
print(os.path.exists(file_path))Solution
Step 1: Analyze download setup
Preferences set to save PDF automatically to '/tmp/downloads'.Step 2: Check file existence print
After download, os.path.exists returns True if file is present.Final Answer:
True -> Option AQuick Check:
File exists after download = True [OK]
- Assuming print outputs file path string
- Expecting False without download
- Confusing syntax or runtime errors
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.dir', '/tmp/downloads')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')
driver = webdriver.Firefox(profile)
driver.get('http://example.com/data.csv')
Solution
Step 1: Check webdriver.Firefox() usage
Firefox expects profile passed as firefox_profile=profile, not just profile.Step 2: Confirm other settings
MIME type 'text/csv' and folder path are correct; no options parameter needed here.Final Answer:
Incorrect argument name; should be firefox_profile=profile -> Option CQuick Check:
Use firefox_profile=profile argument = D [OK]
- Passing profile as positional argument
- Changing MIME type unnecessarily
- Using relative folder path
Solution
Step 1: Understand Selenium's download verification limits
Selenium cannot access browser download history or alerts for downloads.Step 2: Use file system check
Checking file existence with os.path.exists() in the download folder confirms the file saved.Final Answer:
Use os.path.exists() to check the file in the download folder -> Option DQuick Check:
File system check confirms download = A [OK]
- Trying to read browser download history
- Waiting for non-existent alert popups
- Searching page source for downloaded file
Ready to prove it?
Pass the test and this pattern moves unknown
