Downloading files is a common requirement in end-to-end testing scenarios, such as verifying reports, invoices, or exported data. Playwright makes this process seamless by providing built-in APIs to handle downloads efficiently across browsers.
Overview
When using Playwright, file downloads are managed by capturing the download event that occurs whenever a file begins to download.
Downloading a File in Playwright
- Enable downloads: Launch a browser context with acceptDownloads: true.
- Trigger the download: Perform the action that initiates the file download (e.g., click a “Download” button).
- Wait for the download event: Use page.waitForEvent(‘download’) (JavaScript) or page.expect_download() (Python) to capture the download.
- Save the file: Use download.saveAs(‘path/filename.ext’) to store the file at a desired location.
- Access file details: Retrieve the file’s path or suggested name using download.path() or download.suggested_filename().
- Validate the result: Verify the file exists and matches expected content or size for test validation.
This article explores how to manage file downloads in Playwright, covering setup, JavaScript and Python examples, handling custom paths, and best practices for reliable automation.
Understanding File Downloads in Playwright
In Playwright, file downloads are handled through a dedicated download event that is triggered whenever a file begins downloading in the browser. Unlike traditional automation tools that rely on fixed download paths, Playwright provides direct access to the downloaded file object, allowing you to monitor, control, and save downloads programmatically.
When a download starts, Playwright emits a download event that can be captured using page.waitForEvent(‘download’) in JavaScript or page.expect_download() in Python. This gives you access to useful methods such as:
- download.path() – retrieves the temporary file path.
- download.suggestedFilename() – returns the file name suggested by the browser.
- download.saveAs(path) – saves the file to a custom directory or location.
By default, Playwright stores downloaded files in a temporary directory and automatically cleans them up once the browser context is closed. To retain the files, you must explicitly save them using the saveAs() method.
This event-driven mechanism ensures that file downloads can be handled consistently across different browsers and platforms, making it easier to automate real-world scenarios such as exporting reports, downloading receipts, or validating dynamically generated files.
Setting Up Playwright Environment
Before you can automate file downloads, you need to set up a proper Playwright environment. Playwright supports multiple languages-including JavaScript, TypeScript, and Python-so the setup process varies slightly depending on your preferred language.
Here’s how to get started:
1. Install Playwright
For Node.js / JavaScript / TypeScript:
npm install playwright
For Python:
pip install playwright
After installation, you’ll need to download the browser binaries:
npx playwright install
Or
playwright install
2. Verify Installation
Check if Playwright is installed correctly by running:
npx playwright –version
Or
playwright –version
You should see the installed version printed in the console.
3. Create a Browser Context with Download Support
When automating downloads, ensure that downloads are explicitly allowed:
const context = await browser.newContext({ acceptDownloads: true });or in Python:
context = await browser.new_context(accept_downloads=True)
This setting enables Playwright to handle and store file downloads for your automated tests.
Once the environment is ready, you can proceed to write scripts that trigger, capture, and save file downloads in your preferred language.
How to Download a File in Playwright (JavaScript Example)
Downloading a file in Playwright using JavaScript is a straightforward process that relies on capturing the download event and then saving the file to a desired location. Below is a simple step-by-step guide with an example:
Step-by-Step Example
const { chromium } = require(‘playwright’);
(async () => {
// Launch browser and create a new context with download support
const browser = await chromium.launch();
const context = await browser.newContext({ acceptDownloads: true });
const page = await context.newPage();
// Navigate to the page containing the download link or button
await page.goto(‘https://example.com/download’);
// Wait for the download event to be triggered after clicking the download button
const [download] = await Promise.all([
page.waitForEvent(‘download’), // Waits for the download to start
page.click(‘#downloadButton’) // Triggers the download
]);
// Save the downloaded file to a specific location
await download.saveAs(‘downloads/report.pdf’);
// Optional: Get download details
console.log(‘File saved to:’, await download.path());
console.log(‘Suggested filename:’, download.suggestedFilename());
await browser.close();
})();
Explanation of Key Steps
- Enable downloads: The browser context must be initialized with acceptDownloads: true.
- Trigger download: Perform an action like page.click() that starts the file download.
- Wait for the event: page.waitForEvent(‘download’) listens for the download event.
- Save the file: Use download.saveAs(‘path/filename.ext’) to store the file permanently.
- Access details: Retrieve metadata like file name or path using download.suggestedFilename() or download.path().
How to Download a File in Playwright (Python Example)
Downloading a file in Playwright using Python follows a similar event-driven approach as in JavaScript, but with Pythonic syntax and async handling. Below is a practical example to guide you through the process:
Step-by-Step Example
import asyncio
from playwright.async_api import async_playwrightasync def run():
async with async_playwright() as p:
# Launch browser and create a new context with download support
browser = await p.chromium.launch()
context = await browser.new_context(accept_downloads=True)
page = await context.new_page()# Navigate to the page containing the download link or button
await page.goto(“https://example.com/download”)# Wait for the download to begin after clicking the download button
async with page.expect_download() as download_info:
await page.click(“#downloadButton”)
download = await download_info.value# Save the downloaded file to a specific location
await download.save_as(“downloads/report.pdf”)# Optional: Print file details
print(“File saved to:”, await download.path())
print(“Suggested filename:”, download.suggested_filename)await browser.close()
asyncio.run(run())
Explanation of Key Steps
- Enable downloads: Create a browser context with accept_downloads=True to allow Playwright to handle file downloads.
- Trigger the download: Perform an action (like page.click()) that initiates a file download.
- Capture the event: Use the page.expect_download() context manager to wait for and capture the download event.
- Save the file: Use download.save_as(‘path/filename.ext’) to store the file in your preferred directory.
- Access file metadata: Retrieve the file path and suggested filename for validation or logging.
Handling Custom Download Paths
By default, Playwright stores downloaded files in a temporary directory that is automatically cleared when the browser context is closed. However, you can define a custom download path to save files in a specific location, making it easier to organize and verify downloaded content.
Here’s how to manage custom download paths effectively:
1. Configure a browser context with a download directory
You can specify a custom folder path when creating a browser context. This tells Playwright where to store all downloaded files automatically.
JavaScript Example:
const context = await browser.newContext({
acceptDownloads: true,
downloadsPath: ‘downloads/’
});Python Example:
context = await browser.new_context(
accept_downloads=True,
downloads_path=”downloads/”
)
2. Save specific downloads manually (optional)
Even with a default download path set, you can choose to save individual downloads elsewhere using the saveAs() method:
await download.saveAs(‘custom-folder/myfile.pdf’);
await download.save_as(‘custom-folder/myfile.pdf’)
3. Handle dynamic file names
Use Playwright’s suggestedFilename() or suggested_filename property to maintain the original file name from the server:
const filename = download.suggestedFilename();
await download.saveAs(`downloads/${filename}`);
filename = download.suggested_filename
await download.save_as(f”downloads/{filename}”)
4. Verify and clean up files after tests
After downloading, you can verify the file’s existence and size using Node’s fs module or Python’s os and pathlib modules. Cleaning up downloaded files at the end of tests ensures your workspace stays organized and prevents disk bloat.
Defining custom download paths not only improves test reliability but also helps with debugging and post-test analysis, especially when validating multiple file downloads in automated workflows.
Read More: Playwright Test Report: Comprehensive Guide
Validating the Downloaded File
Validating downloaded files is an essential part of end-to-end testing, ensuring that the correct file has been downloaded, saved, and matches the expected content. Playwright provides flexible ways to perform these validations using standard file system operations.
Here’s how you can approach file validation effectively:
- Check file existence: After saving the file, confirm that it exists in the specified download directory. You can use file system utilities (fs in Node.js or os.path in Python) to verify this.
- Validate file name and type: Compare the downloaded file’s name or extension with the expected value. This ensures you’re validating the right file, especially when working with dynamic or timestamped file names.
- Check file size or integrity: Validate that the file size is greater than zero or matches a known value. For more detailed verification, compare file hashes (e.g., MD5 or SHA-256) with the expected checksum.
- Verify file content (if applicable): For text-based files like CSV, JSON, or logs, open and read the file to confirm the presence of expected headers, values, or strings. For binary files like PDFs or images, you can validate metadata or use libraries designed for format verification.
- Clean up after validation: Once validation is complete, consider deleting downloaded files to keep your workspace organized and prevent disk space issues during repeated test runs.
Implementing proper validation ensures your automated tests not only confirm that a download occurred but also that the resulting file is accurate, complete, and usable – a key aspect of reliable browser automation.
Read More: Web Scraping with Playwright
Best Practices for File Download Automation
Automating file downloads in Playwright requires careful handling to ensure reliability, consistency, and efficiency across browsers and environments. Following best practices helps you avoid common pitfalls like incomplete downloads, synchronization issues, or leftover files.
Here are some proven best practices for file download automation:
- Always enable downloads explicitly: Create your browser context with acceptDownloads set to true. This ensures Playwright can properly capture and manage file downloads during test execution.
- Wait for the download event before interacting further: Use page.waitForEvent(‘download’) or page.expect_download() before performing the action that triggers the download. This prevents timing issues and ensures the event is captured accurately.
- Avoid hard-coded paths: Use relative paths or dynamic directories for saving files. This makes your tests portable across different machines and CI environments.
- Handle dynamic file names carefully: Use the browser’s suggested filename or dynamically generate one to avoid overwriting files during parallel test runs.
- Validate downloaded files thoroughly: Don’t just check for file existence – verify file size, type, and content to ensure data integrity and correctness.
- Clean up after tests: Remove downloaded files once validation is complete to prevent disk clutter, especially when running frequent or large-scale test suites.
- Use consistent folder structures: Maintain a clear directory structure for storing test downloads (e.g., per test case or per execution). This simplifies debugging and result tracking.
Enhance File Download Testing with BrowserStack Automate
When you need to test file downloads at scale, running everything on local machines can quickly become slow, brittle, and hard to maintain. BrowserStack Automate lets you run your Playwright download tests in the cloud on a wide range of real browsers and operating systems, without managing any local infrastructure.
With BrowserStack Automate, you can:
- Run Playwright tests on 3,500+ real browsers and devices instead of maintaining your own grid or VMs.
- Scale your download test coverage using parallel execution to significantly reduce total build time.
- Integrate with your existing pipelines (CI tools like Jenkins, GitHub Actions, and others) so download tests run automatically as part of your releases.
- Debug failures faster with rich artifacts such as videos, console logs, and network logs captured for every run.
You can plug your existing Playwright tests into BrowserStack with minimal changes, then continue validating downloaded files using the same logic you use locally, just with more browsers, more environments, and far less maintenance.
Conclusion
Handling file downloads in Playwright is a key aspect of building complete and reliable end-to-end tests. By understanding how Playwright manages download events, configuring custom paths, and validating downloaded files, you can ensure accurate and consistent results across browsers.
Following best practices, such as enabling downloads explicitly, using event-based waits, and cleaning up files after tests, helps maintain stable and efficient automation workflows.
And as projects scale, running these Playwright tests on a cloud platform like BrowserStack Automate provides greater coverage, speed, and reliability without the burden of local setup or maintenance.
Useful Resources for Playwright
- Playwright Automation Framework
- Playwright Java Tutorial
- Playwright Python tutorial
- Playwright Debugging
- End to End Testing using Playwright
- Visual Regression Testing Using Playwright
- Mastering End-to-End Testing with Playwright and Docker
- Page Object Model in Playwright
- Scroll to Element in Playwright
- Understanding Playwright Assertions
- Cross Browser Testing using Playwright
- Playwright Selectors
- Playwright and Cucumber Automation
Tool Comparisons:




