Skip to main content
SeleniumDecoded
Chapter 5 · Lesson 10 of 11 Advanced Features
On this page

Testing File Downloads

Set download folders in Chrome, Edge and Firefox, wait for downloads to finish, use the Selenium Grid downloads API, and verify file contents, not just names.

Selenium 4 Stable 8 min read · Updated · Verified against Selenium 4.52.0

Exports, invoices, reports and backups are features users depend on, and “the CSV export is empty” is the kind of bug that reaches production because nobody tested it end to end. WebDriver itself has no “download” command; the browser downloads files to disk on its own. Testing a download therefore means three things: telling the browser where to save files without prompting, waiting until the file is complete, and getting the file to your test process so you can check what is in it.

That last step is easy locally and hard on Selenium Grid, where the file lands on a remote node. Selenium 4 has a dedicated Grid downloads API for exactly that problem.

Decide First: Do You Need the Browser at All?

Before building download plumbing, consider whether the test is really about the browser. Often the export is a plain HTTP GET behind a link. You can:

  1. Read the link’s href with Selenium.
  2. Copy the session cookies from the driver into an HTTP client.
  3. Download the file directly and assert on it.

This is faster and avoids every issue in this lesson. It does not cover downloads generated client-side (Blob URLs from JavaScript), downloads triggered by form POSTs with complex state, or “does the browser actually save it” scenarios. For those, keep reading.

Configuring the Download Directory

By default browsers either prompt the user or save to the OS Downloads folder. Configure each browser to save silently into a per-test directory you control. A unique directory per test (or per worker) is important for parallel runs; otherwise tests read each other’s files.

Chrome and Edge: silent downloads to a chosen folder
Selenium 4 Stable
Path downloadDir = Files.createTempDirectory("downloads-");
Map<String, Object> prefs = new HashMap<>();
prefs.put("download.default_directory", downloadDir.toAbsolutePath().toString());
prefs.put("download.prompt_for_download", false);
prefs.put("download.directory_upgrade", true);
prefs.put("safebrowsing.enabled", true);
ChromeOptions options = new ChromeOptions(); // EdgeOptions takes the same prefs
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
import tempfile
download_dir = tempfile.mkdtemp(prefix="downloads-")
options = webdriver.ChromeOptions() # webdriver.EdgeOptions() takes the same prefs
options.add_experimental_option("prefs", {
"download.default_directory": download_dir,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True,
})
driver = webdriver.Chrome(options=options)
const os = require('os');
const path = require('path');
const fs = require('fs');
const chrome = require('selenium-webdriver/chrome');
const downloadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'downloads-'));
const options = new chrome.Options().setUserPreferences({
'download.default_directory': downloadDir,
'download.prompt_for_download': false,
'download.directory_upgrade': true,
'safebrowsing.enabled': true,
});
const driver = await new Builder().forBrowser('chrome').setChromeOptions(options).build();
var downloadDir = Directory.CreateTempSubdirectory("downloads-").FullName;
var options = new ChromeOptions(); // EdgeOptions takes the same prefs
options.AddUserProfilePreference("download.default_directory", downloadDir);
options.AddUserProfilePreference("download.prompt_for_download", false);
options.AddUserProfilePreference("download.directory_upgrade", true);
options.AddUserProfilePreference("safebrowsing.enabled", true);
var driver = new ChromeDriver(options);

The directory must be an absolute path that exists on the machine running the browser. With Docker or Grid, a path on your laptop means nothing to the node; see the Grid section below.

Firefox: download preferences
Selenium 4 Stable
FirefoxOptions options = new FirefoxOptions();
options.addPreference("browser.download.folderList", 2); // 2 = custom directory
options.addPreference("browser.download.dir", downloadDir.toAbsolutePath().toString());
options.addPreference("browser.download.useDownloadDir", true);
options.addPreference("browser.download.manager.showWhenStarting", false);
options.addPreference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/pdf,application/zip,application/octet-stream");
options.addPreference("pdfjs.disabled", true); // save PDFs instead of opening them
WebDriver driver = new FirefoxDriver(options);
options = webdriver.FirefoxOptions()
options.set_preference("browser.download.folderList", 2) # 2 = custom directory
options.set_preference("browser.download.dir", download_dir)
options.set_preference("browser.download.useDownloadDir", True)
options.set_preference("browser.download.manager.showWhenStarting", False)
options.set_preference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/pdf,application/zip,application/octet-stream")
options.set_preference("pdfjs.disabled", True) # save PDFs instead of opening them
driver = webdriver.Firefox(options=options)
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options()
.setPreference('browser.download.folderList', 2)
.setPreference('browser.download.dir', downloadDir)
.setPreference('browser.download.useDownloadDir', true)
.setPreference('browser.download.manager.showWhenStarting', false)
.setPreference('browser.helperApps.neverAsk.saveToDisk',
'text/csv,application/pdf,application/zip,application/octet-stream')
.setPreference('pdfjs.disabled', true);
const driver = await new Builder().forBrowser('firefox').setFirefoxOptions(options).build();
var options = new FirefoxOptions();
options.SetPreference("browser.download.folderList", 2);
options.SetPreference("browser.download.dir", downloadDir);
options.SetPreference("browser.download.useDownloadDir", true);
options.SetPreference("browser.download.manager.showWhenStarting", false);
options.SetPreference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/pdf,application/zip,application/octet-stream");
options.SetPreference("pdfjs.disabled", true);
var driver = new FirefoxDriver(options);

Recent Firefox versions save most file types without prompting once useDownloadDir is true, so the MIME-type list matters less than it used to, but it does no harm and helps with older versions.

BrowserHow to set the directoryNotes
Chrome / Edgeprefs user preferencesAlso works headless
Firefoxbrowser.download.* preferencesDisable the built-in PDF viewer to save PDFs
SafariNot configurable via WebDriverDownloads go to the user’s Downloads folder; prefer the HTTP approach

For a quick reference, see the set download directory recipe.

Waiting for the Download to Finish

Clicking the download link returns immediately. The file may not exist yet, may exist under a temporary name, or may be partly written. Browsers use temporary files during download:

BrowserTemporary file while downloading
Chrome / Edgename.ext.crdownload (or Unconfirmed 1234.crdownload)
Firefoxname.ext.part, often alongside a zero-byte name.ext placeholder

A correct wait checks for the expected final file and for the absence of temporary files, and ideally that the size has stopped changing.

Wait until a completed download appears
Selenium 4 Stable
Path waitForDownload(Path dir, String extension, Duration timeout) {
return new FluentWait<>(dir)
.withTimeout(timeout)
.pollingEvery(Duration.ofMillis(250))
.ignoring(IOException.class, UncheckedIOException.class)
.until(d -> {
try (Stream<Path> files = Files.list(d)) {
List<Path> all = files.toList();
boolean inProgress = all.stream().anyMatch(p -> {
String n = p.getFileName().toString();
return n.endsWith(".crdownload") || n.endsWith(".part") || n.endsWith(".tmp");
});
if (inProgress) return null;
return all.stream()
.filter(p -> p.getFileName().toString().endsWith(extension))
.filter(p -> p.toFile().length() > 0)
.findFirst()
.orElse(null);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
driver.findElement(By.cssSelector("[data-testid='export-csv']")).click();
Path csv = waitForDownload(downloadDir, ".csv", Duration.ofSeconds(30));
import os
from pathlib import Path
from selenium.webdriver.support.wait import WebDriverWait
TEMP_SUFFIXES = (".crdownload", ".part", ".tmp")
def wait_for_download(driver, directory, extension, timeout=30):
def completed(_):
names = os.listdir(directory)
if any(n.endswith(TEMP_SUFFIXES) for n in names):
return False
for n in names:
p = Path(directory, n)
if n.endswith(extension) and p.stat().st_size > 0:
return p
return False
return WebDriverWait(driver, timeout, poll_frequency=0.25).until(completed)
driver.find_element(By.CSS_SELECTOR, "[data-testid='export-csv']").click()
csv_path = wait_for_download(driver, download_dir, ".csv")
const TEMP_SUFFIXES = ['.crdownload', '.part', '.tmp'];
async function waitForDownload(driver, dir, extension, timeout = 30000) {
return driver.wait(() => {
const names = fs.readdirSync(dir);
if (names.some((n) => TEMP_SUFFIXES.some((s) => n.endsWith(s)))) return false;
const done = names.find(
(n) => n.endsWith(extension) && fs.statSync(path.join(dir, n)).size > 0
);
return done ? path.join(dir, done) : false;
}, timeout, 'Download did not complete');
}
await driver.findElement(By.css("[data-testid='export-csv']")).click();
const csvPath = await waitForDownload(driver, downloadDir, '.csv');
string WaitForDownload(IWebDriver driver, string dir, string extension, TimeSpan timeout)
{
var tempSuffixes = new[] { ".crdownload", ".part", ".tmp" };
var wait = new WebDriverWait(driver, timeout) { PollingInterval = TimeSpan.FromMilliseconds(250) };
wait.IgnoreExceptionTypes(typeof(IOException));
return wait.Until(_ =>
{
var files = Directory.GetFiles(dir);
if (files.Any(f => tempSuffixes.Any(s => f.EndsWith(s))))
return null;
return files.FirstOrDefault(f => f.EndsWith(extension) && new FileInfo(f).Length > 0);
});
}
driver.FindElement(By.CssSelector("[data-testid='export-csv']")).Click();
var csvPath = WaitForDownload(driver, downloadDir, ".csv", TimeSpan.FromSeconds(30));

Practical advice for the wait:

  • Start from an empty directory. If the folder already contains report.csv from an earlier test, the wait succeeds instantly with the wrong file. A fresh temp directory per test solves this; otherwise record the files present before clicking and look only for new ones.
  • Expect name collisions. Browsers rename duplicates to report (1).csv. Another reason to start from an empty directory.
  • Size the timeout to the file. A 30-second timeout is generous for a CSV and short for a 500 MB backup. Large downloads may need a size-stable check (same size on two consecutive polls) as an extra guard.

The wait for download recipe has a compact version of this helper.

Downloads on Selenium Grid

On Grid, the browser runs on a node. The file lands in the node’s filesystem, which your test cannot read. Selenium 4 solves this with managed downloads: the node collects files downloaded in your session and exposes them over the Grid’s HTTP API.

Enable managed downloads

Two switches are required:

  1. The node must be started with managed downloads enabled:
Terminal window
java -jar selenium-server-<version>.jar node --enable-managed-downloads true

With the official Docker images, set SE_NODE_ENABLE_MANAGED_DOWNLOADS=true on the node container.

  1. The session must ask for it with the se:downloadsEnabled capability. The Options classes have a helper for this.

When both are set, the node configures the browser’s download directory for you; do not set download.default_directory yourself.

Download a file through the Grid downloads API
Selenium 4 Stable
ChromeOptions options = new ChromeOptions();
options.setEnableDownloads(true); // sets se:downloadsEnabled
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://grid:4444"), options);
driver.get("https://app.example.com/reports");
driver.findElement(By.cssSelector("[data-testid='export-csv']")).click();
HasDownloads downloads = (HasDownloads) driver;
List<String> files = new WebDriverWait(driver, Duration.ofSeconds(30))
.until(d -> {
List<String> names = downloads.getDownloadableFiles();
return names.stream().anyMatch(n -> n.endsWith(".csv")) ? names : null;
});
Path target = Files.createTempDirectory("grid-downloads-");
String fileName = files.stream().filter(n -> n.endsWith(".csv")).findFirst().orElseThrow();
downloads.downloadFile(fileName, target);
Path csv = target.resolve(fileName);
downloads.deleteDownloadableFiles(); // clean up the node
options = webdriver.ChromeOptions()
options.enable_downloads = True # sets se:downloadsEnabled
driver = webdriver.Remote(command_executor="http://grid:4444", options=options)
driver.get("https://app.example.com/reports")
driver.find_element(By.CSS_SELECTOR, "[data-testid='export-csv']").click()
WebDriverWait(driver, 30).until(
lambda d: any(n.endswith(".csv") for n in d.get_downloadable_files()))
file_name = next(n for n in driver.get_downloadable_files() if n.endswith(".csv"))
target = tempfile.mkdtemp(prefix="grid-downloads-")
driver.download_file(file_name, target)
csv_path = Path(target, file_name)
driver.delete_downloadable_files() # clean up the node
const options = new chrome.Options();
options.set('se:downloadsEnabled', true);
const driver = await new Builder()
.usingServer('http://grid:4444')
.forBrowser('chrome')
.setChromeOptions(options)
.build();
await driver.get('https://app.example.com/reports');
await driver.findElement(By.css("[data-testid='export-csv']")).click();
const fileName = await driver.wait(async () => {
const names = await driver.getDownloadableFiles();
return names.find((n) => n.endsWith('.csv')) || false;
}, 30000);
const target = fs.mkdtempSync(path.join(os.tmpdir(), 'grid-downloads-'));
await driver.downloadFile(fileName, target);
const csvPath = path.join(target, fileName);
await driver.deleteDownloadableFiles(); // clean up the node
var options = new ChromeOptions { EnableDownloads = true }; // sets se:downloadsEnabled
var driver = new RemoteWebDriver(new Uri("http://grid:4444"), options);
driver.Navigate().GoToUrl("https://app.example.com/reports");
driver.FindElement(By.CssSelector("[data-testid='export-csv']")).Click();
var fileName = new WebDriverWait(driver, TimeSpan.FromSeconds(30)).Until(d =>
driver.GetDownloadableFiles().FirstOrDefault(n => n.EndsWith(".csv")));
var target = Directory.CreateTempSubdirectory("grid-downloads-").FullName;
driver.DownloadFile(fileName, target);
var csvPath = Path.Combine(target, fileName);
driver.DeleteDownloadableFiles(); // clean up the node

getDownloadableFiles() only lists completed files, so polling it doubles as the completion wait. Call deleteDownloadableFiles() between downloads in the same session if you need to distinguish them, and at the end of the test so files do not accumulate on long-lived nodes (they are also removed when the session ends).

Warning: Selenium 4.49 removed the old, deprecated GET /session/{id}/se/files/{fileName} endpoint from the Java client. If you have custom code (or an old helper library) that calls that URL directly, it now fails. Switch to getDownloadableFiles() and downloadFile(), which use the supported endpoint. 4.49 also fixed a Grid bug with downloading files whose names contain spaces, so upgrade if you hit that.

The JavaScript example sets the raw capability with options.set(...), which works in every binding. Check the JavaScript API docs for your version if you prefer a typed helper and want to confirm the download method names.

Cloud providers

Commercial grids implement downloads in their own ways: some support the Selenium managed downloads API, others expose a provider-specific endpoint or a “files” tab in their dashboard. Check the provider’s docs; the polling-and-verify structure stays the same.

BiDi Download Events

WebDriver BiDi defines browsing context events for downloads: browsingContext.downloadWillBegin fires when a download starts (with the URL and suggested filename), and newer browser versions add a downloadEnd event reporting completion or cancellation. These are push events rather than polling, and they work without filesystem access.

Support varies by browser version and by binding, and the convenience APIs around them are still settling. Use them as an extra signal (“the click actually triggered a download, and it was called report-2026-11.csv”), and keep the filesystem or Grid API check for the final verification. The WebDriver BiDi lesson covers how to subscribe to events in each language.

Verifying the Contents

A test that only checks “a file appeared” passes when the export contains a stack trace, an empty table, or the wrong month. Assert on what is inside.

Verify a CSV export's header and rows
Selenium 4 Stable
List<String> lines = Files.readAllLines(csv, StandardCharsets.UTF_8);
assertEquals("Order,Customer,Status,Total", lines.get(0).replace("\uFEFF", "")); // strip BOM
assertEquals(expectedOrders.size() + 1, lines.size());
assertTrue(lines.stream().anyMatch(l -> l.startsWith("INV-1042,Ada Lovelace,Paid,")));
import csv
with open(csv_path, newline="", encoding="utf-8-sig") as f: # utf-8-sig strips a BOM
rows = list(csv.DictReader(f))
assert list(rows[0].keys()) == ["Order", "Customer", "Status", "Total"]
assert len(rows) == len(expected_orders)
assert any(r["Order"] == "INV-1042" and r["Status"] == "Paid" for r in rows)
const text = fs.readFileSync(csvPath, 'utf8').replace(/^\uFEFF/, '');
const lines = text.trim().split(/\r?\n/);
assert.strictEqual(lines[0], 'Order,Customer,Status,Total');
assert.strictEqual(lines.length, expectedOrders.length + 1);
assert.ok(lines.some((l) => l.startsWith('INV-1042,Ada Lovelace,Paid,')));
var lines = File.ReadAllLines(csvPath, Encoding.UTF8); // ReadAllLines strips a UTF-8 BOM
Assert.That(lines[0], Is.EqualTo("Order,Customer,Status,Total"));
Assert.That(lines.Length, Is.EqualTo(expectedOrders.Count + 1));
Assert.That(lines.Any(l => l.StartsWith("INV-1042,Ada Lovelace,Paid,")), Is.True);

Content checks by file type:

TypeWhat to checkTypical library
CSVHeader, row count, specific rows, encoding/BOM, delimiterBuilt-in CSV readers
Excel (.xlsx)Sheet names, header row, cell values and typesApache POI, openpyxl, exceljs, ClosedXML
PDFExtracted text contains key values; page countPDFBox, pypdf, pdf-parse, PdfPig
ZIPEntry names and sizes; then check entries individuallyBuilt-in zip libraries
JSONSchema and key valuesBuilt-in JSON parsers
AnyFilename pattern, non-zero size, MIME type via magic bytesBuilt-in file APIs

Use a known dataset for export tests: seed the data via API, export, and compare against what you seeded. Asserting on whatever happens to be in a shared environment is how export tests become flaky. The verify downloaded file recipe has more format examples.

Common Pitfalls

SymptomCauseFix
A “Save as” dialog appears and the test hangsPrompt not disabledSet download.prompt_for_download: false (Chromium) or Firefox prefs
PDF opens in a tab instead of downloadingBuilt-in PDF viewerpdfjs.disabled in Firefox; plugins.always_open_pdf_externally: true in Chromium prefs
Wait passes with the previous test’s fileShared download directoryUnique empty directory per test
File found but empty or truncatedRead while still downloadingCheck for temp files and non-zero, stable size
Works locally, nothing found on GridFile is on the nodeManaged downloads and downloadFile()
Custom code calling /se/files/ fails after upgradingEndpoint removed in 4.49 (Java)Use the downloads API
Chrome blocks the download as “insecure”HTTP download from HTTPS page or Safe BrowsingServe over HTTPS in test env; review Safe Browsing prefs

Summary

  • Consider downloading over HTTP with the session’s cookies when the browser is not the point of the test.
  • Configure a unique, absolute download directory per test via browser preferences.
  • Wait for the final file and the absence of temporary .crdownload/.part files.
  • On Grid, enable managed downloads on the node, set se:downloadsEnabled, and use getDownloadableFiles, downloadFile and deleteDownloadableFiles.
  • Treat BiDi download events as a helpful signal, not yet the sole check.
  • Always verify file contents against known data, not just existence.

Finished this lesson?

Mark it complete to track your progress through the course. Saved in this browser only.

Test yourself Advanced Features 10 questions · intermediate

Related lessons