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.
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:
- Read the link’s
hrefwith Selenium. - Copy the session cookies from the driver into an HTTP client.
- 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.
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 prefsoptions.setExperimentalOption("prefs", prefs);WebDriver driver = new ChromeDriver(options);import tempfile
download_dir = tempfile.mkdtemp(prefix="downloads-")
options = webdriver.ChromeOptions() # webdriver.EdgeOptions() takes the same prefsoptions.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 prefsoptions.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.
FirefoxOptions options = new FirefoxOptions();options.addPreference("browser.download.folderList", 2); // 2 = custom directoryoptions.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 themWebDriver driver = new FirefoxDriver(options);options = webdriver.FirefoxOptions()options.set_preference("browser.download.folderList", 2) # 2 = custom directoryoptions.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 themdriver = 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.
| Browser | How to set the directory | Notes |
|---|---|---|
| Chrome / Edge | prefs user preferences | Also works headless |
| Firefox | browser.download.* preferences | Disable the built-in PDF viewer to save PDFs |
| Safari | Not configurable via WebDriver | Downloads 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:
| Browser | Temporary file while downloading |
|---|---|
| Chrome / Edge | name.ext.crdownload (or Unconfirmed 1234.crdownload) |
| Firefox | name.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.
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 osfrom pathlib import Pathfrom 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.csvfrom 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:
- The node must be started with managed downloads enabled:
java -jar selenium-server-<version>.jar node --enable-managed-downloads trueWith the official Docker images, set SE_NODE_ENABLE_MANAGED_DOWNLOADS=true on the node container.
- The session must ask for it with the
se:downloadsEnabledcapability. 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.
ChromeOptions options = new ChromeOptions();options.setEnableDownloads(true); // sets se:downloadsEnabledRemoteWebDriver 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 nodeoptions = webdriver.ChromeOptions()options.enable_downloads = True # sets se:downloadsEnableddriver = 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 nodeconst 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 nodevar options = new ChromeOptions { EnableDownloads = true }; // sets se:downloadsEnabledvar 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 nodegetDownloadableFiles() 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 togetDownloadableFiles()anddownloadFile(), 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.
List<String> lines = Files.readAllLines(csv, StandardCharsets.UTF_8);
assertEquals("Order,Customer,Status,Total", lines.get(0).replace("\uFEFF", "")); // strip BOMassertEquals(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:
| Type | What to check | Typical library |
|---|---|---|
| CSV | Header, row count, specific rows, encoding/BOM, delimiter | Built-in CSV readers |
| Excel (.xlsx) | Sheet names, header row, cell values and types | Apache POI, openpyxl, exceljs, ClosedXML |
| Extracted text contains key values; page count | PDFBox, pypdf, pdf-parse, PdfPig | |
| ZIP | Entry names and sizes; then check entries individually | Built-in zip libraries |
| JSON | Schema and key values | Built-in JSON parsers |
| Any | Filename pattern, non-zero size, MIME type via magic bytes | Built-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
| Symptom | Cause | Fix |
|---|---|---|
| A “Save as” dialog appears and the test hangs | Prompt not disabled | Set download.prompt_for_download: false (Chromium) or Firefox prefs |
| PDF opens in a tab instead of downloading | Built-in PDF viewer | pdfjs.disabled in Firefox; plugins.always_open_pdf_externally: true in Chromium prefs |
| Wait passes with the previous test’s file | Shared download directory | Unique empty directory per test |
| File found but empty or truncated | Read while still downloading | Check for temp files and non-zero, stable size |
| Works locally, nothing found on Grid | File is on the node | Managed downloads and downloadFile() |
Custom code calling /se/files/ fails after upgrading | Endpoint removed in 4.49 (Java) | Use the downloads API |
| Chrome blocks the download as “insecure” | HTTP download from HTTPS page or Safe Browsing | Serve 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/.partfiles. - On Grid, enable managed downloads on the node, set
se:downloadsEnabled, and usegetDownloadableFiles,downloadFileanddeleteDownloadableFiles. - 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.