How to download a file using Playwright

On This Page Understanding File Downloads in PlaywrightMarch 26, 2026 · 10 min read · Tool Comparison

How to download a file using Playwright

Downloading files is a mutual requirement in end-to-end testing scenario, such as control reports, invoices, or exported data. makes this process seamless by providing built-in APIs to deal downloads expeditiously across browsers.

Overview

When using Playwright, file downloads are cope 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 induct the file download (e.g., click a & # 8220; Download & # 8221; button).
  • Wait for the download case:Use page.waitForEvent (& # 8216; download & # 8217;) (JavaScript) or page.expect_download () (Python) to get the download.
  • Save the file:Use download.saveAs (& # 8216; path/filename.ext & # 8217;) to store the file at a craved location.
  • Access file details:Retrieve the file & # 8217; s itinerary or suggest name using download.path () or download.suggested_filename ().
  • Validate the event:Verify the file exists and lucifer expect content or size for exam validation.

This article search how to grapple file downloads in Playwright, covering setup, JavaScript and Python examples, deal custom paths, and good practices for true 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 mechanization tools that rely on fixed download way, Playwright provides direct access to the download file object, allowing you to monitor, control, and salve downloads programmatically.

When a download starts, Playwright emits a download case that can be enamor utilise page.waitForEvent (& # 8216; download & # 8217;) in or page.expect_download () in Python. This gives you admission to utilitarian methods such as:

  • download.path ()& # 8211; retrieves the irregular file path.
  • download.suggestedFilename ()& # 8211; returns the file name intimate by the browser.
  • download.saveAs (itinerary)& # 8211; saves the file to a custom-made directory or placement.

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 salve them using the saveAs () method.

This event-driven mechanism ensures that file downloads can be handled systematically across different browsers and platforms, making it easier to automate real-world scenarios such as export reports, download receipts, or validating dynamically generated files.

Read More:

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 apparatus process varies slimly depending on your preferred language.

Here & # 8217; s how to get start:

1. Install Playwright

For Node.js / JavaScript / TypeScript:

npm install playwright

For Python:

pip install playwright

After installment, you & # 8217; ll ask to download the browser binaries:

npx playwright install

Or

playwright install

2. Verify Installation

Check if Playwright is installed correctly by scarper:

npx playwright & # 8211; version

Or

playwright & # 8211; version

You should see the installed version printed in the console.

3. Create a Browser Context with Download Support

When automatize downloads, ensure that downloads are explicitly let:

const context = await browser.newContext ({acceptDownloads: true});

or in Python:

context = await browser.new_context (accept_downloads=True)

This background enables Playwright to handle and store file downloads for your machine-controlled tests.

Once the environs is ready, you can proceed to pen 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 procedure that relies on capturing the download event and so saving the file to a desired location. Below is a simple step-by-step guidebook with an example:

Step-by-Step Example

const {Cr} = require (& # 8216; playwright & # 8217;);

(async () = & gt; {
// 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 push
await page.goto (& # 8216; https: //example.com/download & # 8217;);

// Wait for the download event to be triggered after clicking the download button
const [download] = await Promise.all ([
page.waitForEvent (& # 8216; download & # 8217;), // Waits for the download to start
page.click (& # 8216; # downloadButton & # 8217;) // Triggers the download
]);

// Save the downloaded file to a specific location
await download.saveAs (& # 8216; downloads/report.pdf & # 8217;);

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

// Optional: Get download details
console.log (& # 8216; File saved to: & # 8217;, await download.path ());
console.log (& # 8216; Suggested filename: & # 8217;, download.suggestedFilename ());

await browser.close ();
})();

Explanation of Key Steps

  • Enable downloads:The browser circumstance 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 (& # 8216; download & # 8217;) listens for the download event.
  • Save the file:Use download.saveAs (& # 8216; path/filename.ext & # 8217;) to store the file permanently.
  • Access details:Retrieve metadata like file name or path using download.suggestedFilename () or download.path ().

Read More:

How to Download a File in Playwright (Python Example)

Downloading a file in Playwright use Python follows a similar event-driven approach as in JavaScript, but with Pythonic syntax and async manipulation. Below is a practical example to guide you through the procedure:

Step-by-Step Example

import asyncio
from playwright.async_api import async_playwright

async def run ():
async with async_playwright () as p:
# Launch browser and create a new setting 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 bear the download link or button
await page.goto (& # 8220; https: //example.com/download & # 8221;)

# Wait for the download to begin after clicking the download button
async with page.expect_download () as download_info:
await page.click (& # 8220; # downloadButton & # 8221;)
download = await download_info.value

# Save the downloaded file to a specific localisation
await download.save_as (& # 8220; downloads/report.pdf & # 8221;)

# Optional: Print file details
mark (& # 8220; File saved to: & # 8221;, await download.path ())
print (& # 8220; Suggested filename: & # 8221;, 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 () setting manager to wait for and capture the download event.
  • Save the file:Use download.save_as (& # 8216; path/filename.ext & # 8217;) to store the file in your preferred directory.
  • Access file metadata:Retrieve the file path and suggested filename for validation or logging.

Read More:

Handling Custom Download Paths

By default, Playwright shop downloaded files in a temporary directory that is automatically cleared when the browser context is closed. However, you can delimit a impost download path to save files in a specific placement, making it easier to organize and control downloaded message.

Here & # 8217; s how to manage custom download paths effectively:

1. Configure a browser setting with a download directory

You can define a customs booklet path when create a browser context. This tells Playwright where to store all downloaded files mechanically.

JavaScript Example:

const circumstance = await browser.newContext ({
acceptDownloads: true,
downloadsPath: & # 8216; downloads/ & # 8217;
});

Python Example:

context = await browser.new_context (
accept_downloads=True,
downloads_path= & # 8221; downloads/ & # 8221;
)

2. Save specific downloads manually (optional)

Even with a default download path set, you can select to save individual downloads elsewhere using the saveAs () method:

await download.saveAs (& # 8216; custom-folder/myfile.pdf & # 8217;);
await download.save_as (& # 8216; custom-folder/myfile.pdf & # 8217;)

3. Handle active file name

Use Playwright & # 8217; s suggestedFilename () or suggested_filename belongings 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 & # 8221; downloads/ {filename} & # 8221;)

4. Verify and clean up file after trial

After downloading, you can verify the file & # 8217; s existence and size use Node & # 8217; s fs module or Python & # 8217; s os and pathlib faculty. Cleaning up downloaded files at the end of tests ascertain your workspace stays organized and prevents disc bloat.

Defining usage download paths not only improves test reliability but also helps with debugging and post-test analysis, especially when formalize multiple file downloads in machine-driven workflows.

Read More:

Validating the Downloaded File

Validating downloaded files is an essential piece of end-to-end examination, secure that the correct file has been downloaded, saved, and matches the expected content. Playwright provides flexile ways to perform these substantiation expend standard file system operation.

Here & # 8217; s how you can approach file validation effectively:

  • Check file existence:After saving the file, substantiate 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 case:Compare the downloaded file & # 8217; s gens or propagation with the anticipate value. This ensures you & # 8217; re validating the rightfield file, especially when working with dynamic or timestamped file name.
  • Check file size or integrity:Validate that the file size is outstanding 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 message (if applicable):For text-based files like CSV, JSON, or logs, open and read the file to confirm the presence of expected headers, value, or twine. For binary file like PDFs or images, you can validate metadata or use libraries designed for format verification.
  • Clean up after validation:Once validation is accomplished, consider blue-pencil downloaded files to continue your workspace organized and prevent disk space issues during repeated test runs.

Implementing proper validation insure your automated test not only affirm that a download occurred but also that the resulting file is accurate, accomplished, and functional & # 8211; a key aspect of reliable browser automation.

Read More:

Good Practices for File Download Automation

Automating file downloads in Playwright postulate careful handling to ascertain dependableness, consistency, and efficiency across browsers and environments. Following good practices help you avoid mutual pitfalls like incomplete downloads, synchronization issues, or remnant files.

Here are some proven good practices for file download mechanisation:

  • 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 case before interacting further:Use page.waitForEvent (& # 8216; download & # 8217;) or page.expect_download () before perform the action that triggers the download. This prevents timing issues and ensures the case is captured accurately.
  • Avoid hard-coded paths:Use comparative paths or dynamical directories for salvage files. This makes your tests portable across different machines and CI environments.
  • Handle dynamic file names cautiously:Use the browser & # 8217; s suggested filename or dynamically generate one to avoid overwriting files during runs.
  • Validate download files good:Don & # 8217; t just check for file existence & # 8211; verify file sizing, type, and content to ensure data unity and correctness.
  • Clean up after exam:Remove downloaded files formerly validation is complete to keep platter clutter, especially when running frequent or large-scale.
  • Use coherent folder structures:Maintain a clear directory structure for storing test downloads (e.g., per test case or per execution). This simplifies debugging and upshot 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 firmly to maintain. Lashkar-e-Taiba you run your Playwright download tests in the cloud on a wide range of real browsers and operating scheme, 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 reporting using parallel performance to significantly reduce full build clip.
  • Integrate with your existing pipelines (CI tools like, GitHub Actions, and others) so download tests run automatically as piece 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, so continue formalize downloaded files using the same logic you use locally, just with more browsers, more environments, and far less upkeep.

Talk to an Expert

Conclusion

Handling file downloads in Playwright is a key aspect of building consummate and honest. By understanding how Playwright manage download events, configuring custom-made paths, and validating downloaded files, you can ascertain accurate and consistent results across browsers.

Following better exercise, such as enable downloads explicitly, using event-based waits, and pick up file after trial, helps maintain stable and efficient automation workflows.

And as projects scale, escape these Playwright exam on a cloud platform like BrowserStack Automate provides outstanding coverage, hurrying, and dependableness without the burden of local setup or care.

Useful Resources for Playwright

Tool Comparisons:

Tags
7,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free