Bird
Raised Fist0
Selenium Pythontesting~15 mins

File download handling in Selenium Python - Build an Automation Script

Choose your learning style10 modes available
Verify file download functionality
Preconditions (2)
Step 1: Open the browser and navigate to 'https://example.com/download'
Step 2: Locate the download link with id 'download-file'
Step 3: Click the download link
Step 4: Wait for the file to be downloaded to the default download folder
✅ Expected Result: The file named 'sample.pdf' is downloaded successfully to the default download folder
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the file 'sample.pdf' exists in the download folder after clicking the download link
Best Practices:
Use explicit waits to wait for the download link to be clickable
Use a temporary download directory to avoid polluting default folders
Clean up downloaded files after test execution
Use Selenium WebDriver with ChromeOptions to set download preferences
Automated Solution
Selenium Python
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.

Common Mistakes - 4 Pitfalls
Not setting ChromeOptions to specify download directory
Using time.sleep() without checking file existence
Not cleaning up downloaded files after test
Not using explicit waits for the download link
Bonus Challenge

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.

Show Hint

Practice

(1/5)
1. What is the main purpose of setting browser preferences in Selenium for file downloads?
easy
A. To specify the folder where downloaded files are saved automatically
B. To speed up the browser loading time
C. To change the browser's theme
D. To disable JavaScript on the page

Solution

  1. Step 1: Understand browser preferences role

    Browser preferences let you control how downloads behave, like where files save.
  2. Step 2: Identify the correct purpose

    Setting preferences to specify download folder avoids manual prompts and saves files automatically.
  3. Final Answer:

    To specify the folder where downloaded files are saved automatically -> Option A
  4. Quick 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
A. profile.set_preference('browser.download.folderList', '2')
B. profile.set_preference('browser.download.folderList', 2)
C. profile.set_preference('browser.download.folderList', True)
D. profile.set_preference('browser.download.folderList', None)

Solution

  1. Step 1: Recall Firefox preference for download folder

    The 'browser.download.folderList' preference expects an integer: 0 (desktop), 1 (default), 2 (custom folder).
  2. Step 2: Choose correct data type and value

    Using integer 2 sets a custom folder; string or other types cause errors.
  3. Final Answer:

    profile.set_preference('browser.download.folderList', 2) -> Option B
  4. Quick 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
A. True
B. False
C. SyntaxError
D. FileNotFoundError

Solution

  1. Step 1: Analyze download setup

    Preferences set to save PDF automatically to '/tmp/downloads'.
  2. Step 2: Check file existence print

    After download, os.path.exists returns True if file is present.
  3. Final Answer:

    True -> Option A
  4. Quick 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
A. Missing options parameter in webdriver.Firefox()
B. Download folder path must be absolute
C. Incorrect argument name; should be firefox_profile=profile
D. Wrong MIME type for CSV files

Solution

  1. Step 1: Check webdriver.Firefox() usage

    Firefox expects profile passed as firefox_profile=profile, not just profile.
  2. Step 2: Confirm other settings

    MIME type 'text/csv' and folder path are correct; no options parameter needed here.
  3. Final Answer:

    Incorrect argument name; should be firefox_profile=profile -> Option C
  4. Quick 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
A. Check the page source for the file name
B. Check the browser's download history via Selenium API
C. Wait for an alert popup confirming download
D. Use os.path.exists() to check the file in the download folder

Solution

  1. Step 1: Understand Selenium's download verification limits

    Selenium cannot access browser download history or alerts for downloads.
  2. Step 2: Use file system check

    Checking file existence with os.path.exists() in the download folder confirms the file saved.
  3. Final Answer:

    Use os.path.exists() to check the file in the download folder -> Option D
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard