We handle file downloads in tests to check if files are saved correctly. This helps ensure users get the right files from the website.
File download handling in Selenium Python
Introduction
Syntax
Selenium Python
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_experimental_option('prefs', { 'download.default_directory': '/path/to/download/folder', 'download.prompt_for_download': False, 'download.directory_upgrade': True, 'safebrowsing.enabled': True }) driver = webdriver.Chrome(options=options)
Set the download folder path to control where files save.
Disabling prompts lets downloads happen automatically.
Examples
Selenium Python
options.add_experimental_option('prefs', { 'download.default_directory': '/tmp/downloads', 'download.prompt_for_download': False })
Selenium Python
driver.find_element('id', 'downloadButton').click()
Sample Program
This script sets a download folder, opens a page, clicks a download button, waits, and checks if the file is saved.
Selenium Python
import os import time from selenium import webdriver from selenium.webdriver.chrome.options import Options # Set download folder path download_folder = os.path.join(os.getcwd(), 'downloads') os.makedirs(download_folder, exist_ok=True) # Configure Chrome options for automatic download options = Options() options.add_experimental_option('prefs', { 'download.default_directory': download_folder, 'download.prompt_for_download': False, 'download.directory_upgrade': True, 'safebrowsing.enabled': True }) driver = webdriver.Chrome(options=options) try: driver.get('https://example.com/download') # Click the download link/button driver.find_element('id', 'downloadFile').click() # Wait for the file to download (simple wait for demo) time.sleep(5) # Check if file exists in download folder files = os.listdir(download_folder) if files: print(f"Download successful: {files[0]}") else: print("Download failed: No files found") finally: driver.quit()
Important Notes
Always set a unique download folder per test to avoid confusion.
Use explicit waits or check file size to confirm download completion in real tests.
Adjust file name checks based on expected download file names.
Summary
Set browser preferences to control download folder and disable prompts.
Trigger downloads by clicking the right page element.
Verify downloads by checking the file system for saved files.
Practice
1. What is the main purpose of setting browser preferences in Selenium for file downloads?
easy
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]
Hint: Remember: preferences set download folder and disable prompts [OK]
Common Mistakes:
- Thinking preferences speed up browser loading
- Confusing download folder with browser theme
- Assuming preferences disable JavaScript
2. Which of the following is the correct way to set Firefox preferences in Selenium to automatically download PDF files to a folder without prompt?
easy
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]
Hint: Use integer 2, not string, for custom download folder [OK]
Common Mistakes:
- Passing '2' as string instead of integer
- Using boolean True instead of integer
- Passing None which disables setting
3. Given this Selenium Python code snippet, what will be the output if the file is downloaded successfully?
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))medium
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]
Hint: os.path.exists returns True if file is saved correctly [OK]
Common Mistakes:
- Assuming print outputs file path string
- Expecting False without download
- Confusing syntax or runtime errors
4. Identify the error in this Selenium Python code for downloading a CSV file:
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')
medium
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]
Hint: Pass profile with firefox_profile=profile keyword [OK]
Common Mistakes:
- Passing profile as positional argument
- Changing MIME type unnecessarily
- Using relative folder path
5. You want to verify that a file named 'report.xlsx' has been downloaded successfully using Selenium Python. Which approach is best to confirm the download in an automated test?
hard
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]
Hint: Verify downloads by checking file presence on disk [OK]
Common Mistakes:
- Trying to read browser download history
- Waiting for non-existent alert popups
- Searching page source for downloaded file
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
