0
0
Selenium Pythontesting~15 mins

File download handling in Selenium Python - Build an Automation Script

Choose your learning style9 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