Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 35 ยท Interacting with the Page

File Uploads, Downloads and Screenshots

Handle files in Selenium: upload with send_keys on file inputs, set a download directory and wait for the file, and take element and full-page screenshots.

Browsers are also file tools. Users attach a CV to a job application, export a report as CSV, and send a screenshot to a bug tracker. Automated tests need to do the same, and each of these tasks touches something Selenium cannot see: the operating system's file dialog, the browser's download folder, and the pixels the screen shows.

This lesson shows the established approach for each. You will upload a file without ever opening the native file dialog, configure and watch a download directory, and capture screenshots of the page or a single element, including the base64 form that reports and bug trackers often use.

Selenium and a browser cannot run on this site, so the Selenium lines are read-only. The runnable examples are Node.js stand-ins, run on a server, that really write, rename and read files, so you can watch the file logic that surrounds the browser calls.

Uploading a file

The native "choose a file" dialog belongs to the operating system, and WebDriver cannot drive it. You do not need to. A file chooser is an <input type="file"> element, and you can give it a path directly with send_keys:

HTML
<input type="file" id="cv" name="cv" accept=".pdf">
Python
import os
from selenium.webdriver.common.by import By

cv_path = os.path.abspath("fixtures/cv.pdf")

driver.find_element(By.ID, "cv").send_keys(cv_path)
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()

The rules to remember:

  • Never click the file input or its button. Clicking opens the native dialog, and your script then hangs, because Selenium cannot reach it.
  • Use an absolute path that exists on the machine where the browser runs. A relative path or a wrong path produces an error or an empty selection.
  • For an input with the multiple attribute, you can pass several paths in one string separated by a newline: "/abs/one.png\n/abs/two.png".
  • Many designs hide the real input and show a styled button. If the input has display: none, send_keys can fail with ElementNotInteractableException. Ask developers to keep it technically visible (for example with zero opacity), or reveal it from your test with driver.execute_script("arguments[0].style.display = 'block'", el) as a last resort.
  • When the browser runs on another machine, such as a Selenium Grid node, the path must exist there. The Python and Java bindings provide a file detector (LocalFileDetector) that sends your local file to the remote machine first; you set it on the remote driver before using send_keys.

After sending the path, check the page: most sites show the file name next to the input. Assert that, rather than assuming the upload worked.

Three file jobs

Upload send_keys(path) on the file input.
Download Set a folder, then wait for the file.
Screenshot Page, element or base64 string.

The native dialogs are never touched.

1 / 2

Downloads

When a user clicks "Export", the browser saves a file into a folder without any page elements involved. WebDriver cannot see the file, so a download test has two jobs: tell the browser where to save and not to ask, then wait for the file on disk and check it.

Chrome and Edge take their settings from preferences:

Python
import tempfile
from selenium import webdriver

download_dir = tempfile.mkdtemp(prefix="dl-")

options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", {
    "download.default_directory": download_dir,
    "download.prompt_for_download": False,
})
driver = webdriver.Chrome(options=options)

Firefox uses preferences with different names, and it needs to be told which file types to save without a prompt:

Python
options = webdriver.FirefoxOptions()
options.set_preference("browser.download.folderList", 2)          # 2 = use a custom folder
options.set_preference("browser.download.dir", download_dir)
options.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/pdf")
driver = webdriver.Firefox(options=options)

Preference names are browser internals that change between releases, so treat these as a starting point and consult the documentation of your browser version. Use a fresh temporary directory per test: an old file left from a previous run would otherwise make a failing test pass.

Next, wait for the file. Browsers write a partial file first (.crdownload in Chrome, .part in Firefox) and rename it when the transfer completes. A good wait helper ignores partial files and polls until a finished one appears, or time runs out:

Python
import time, pathlib

def wait_for_download(folder, timeout=15):
    deadline = time.time() + timeout
    while time.time() < deadline:
        files = [p for p in pathlib.Path(folder).iterdir()
                 if p.suffix not in (".crdownload", ".part", ".tmp")]
        if files:
            return files[0]
        time.sleep(0.2)
    raise TimeoutError(f"no finished download in {folder}")

Finally, check the result: the name, a non-zero size and some of the content. For a CSV, read the header line.

A stand-in: waiting for a download

The model below plays the browser: it writes a partial file, appends data in pieces and renames it when complete. The helper polls like the Python version above. It uses a real temporary folder and real files on the machine that runs the code.

Node.js Wait for a finished download

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first line shows the partial file that a naive "does any file exist?" check would wrongly accept. Ignoring partial files and verifying the content is what makes the real helper trustworthy.

Screenshots

A screenshot is the best evidence of what the browser actually showed. Selenium can save the visible area, return it as bytes or text, and capture a single element:

Python
driver.save_screenshot("artifacts/home.png")        # file; returns True on success
png_bytes = driver.get_screenshot_as_png()          # raw PNG bytes
b64 = driver.get_screenshot_as_base64()             # base64 text, easy to embed in reports

heading = driver.find_element(By.TAG_NAME, "h1")
heading.screenshot("artifacts/heading.png")         # just that element

An element screenshot crops to the element's box, which makes visual checks and bug reports far more precise. The element must be visible, and Selenium scrolls it into view first.

What counts as "the whole page" depends on the browser:

  • A standard save_screenshot captures the visible viewport, so content below the fold is missing.
  • Firefox offers a real full-page capture: driver.get_full_page_screenshot_as_file("full.png").
  • In Chrome, a common approach is to resize the window to the document's height before the shot, or to use the DevTools Protocol (see DevTools Protocol and BiDi).

The base64 form is a text encoding of the PNG bytes, safe to put in JSON or an HTML report: <img src="data:image/png;base64,...">. To get a file back, decode it. Always validate captured images in a test run, since a blank or tiny image is a common symptom of a page that had not finished rendering. Screenshots also belong in your failure handling, which a later lesson covers in Flaky Tests and Debugging.

A stand-in: base64 screenshots and upload checks

Without a browser we cannot capture real pixels, but we can show the file work: decode a base64 PNG, check its signature and dimensions, save it, and validate an upload path the way a careful helper would before calling send_keys.

Node.js Decode, verify and save a base64 screenshot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The decoded bytes begin with the PNG signature, and the image header yields the size. The same checks, run against a real screenshot, catch a corrupted file early. The upload helper rejects the three most common mistakes before the browser is involved.

Habits for file work

  • Never use real data. Upload and download fixtures should be small test files created for the suite, not customer documents.
  • One temp folder per test, removed at the end, so files never leak between runs.
  • Archive screenshots as artifacts in your continuous integration job, named after the test, so a failure can be investigated without rerunning it.
  • Assert on content, not only existence: a CSV with only a header row is a real bug.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you attach a file to <input type="file"> in Selenium?

    send_keys with an absolute path sets the file directly. Clicking the input opens a native dialog that WebDriver cannot control.
  2. 2. Why should a download helper ignore files ending in .crdownload or .part?

    Treating a partial file as finished would make the test read incomplete data. Wait until a file without those suffixes appears.
  3. 3. What does driver.get_screenshot_as_base64() return?

    It returns text that encodes the PNG bytes, convenient for JSON and for embedding in HTML reports with a data: URL.
  4. 4. Why use a fresh temporary download directory for each test?

    If an old file with the expected name is already in the folder, the wait succeeds even when the new download never happened.

Summary

  • Upload by calling send_keys(absolute_path) on the <input type="file">; never click it, and use a file detector when the browser runs remotely.
  • For downloads, set the browser's download folder and disable the prompt (preference names differ per browser), use a fresh folder per test, wait for a finished file, then verify name, size and content.
  • save_screenshot, get_screenshot_as_png and get_screenshot_as_base64 capture the viewport; element.screenshot captures one element; full-page capture depends on the browser.
  • Base64 screenshots are text and can be embedded in reports; decode and validate them in tests.
  • Use small test fixtures and keep screenshots as run artifacts.

Next, learn why timing makes tests fail and how to fix it in Why Tests Need Waits.