How to download a file using Playwright
On This Page Understanding File Downloads in PlaywrightMarch 26, 2026 · 10 min read · Tool Comparison
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. 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 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. 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: 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: 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: For Node.js / JavaScript / TypeScript: For Python: After installment, you & # 8217; ll ask to download the browser binaries: Or Check if Playwright is installed correctly by scarper: Or You should see the installed version printed in the console. When automatize downloads, ensure that downloads are explicitly let: or in Python: 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. 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 (async () = & gt; { // Navigate to the page containing the download link or push // Wait for the download event to be triggered after clicking the download button // Save the downloaded file to a specific location 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 await browser.close (); Explanation of Key Steps Read More: 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 async def run (): # Navigate to the page bear the download link or button # Wait for the download to begin after clicking the download button # Save the downloaded file to a specific localisation # Optional: Print file details await browser.close () asyncio.run (run ()) Explanation of Key Steps Read More: 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: Python Example: 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: 3. Handle active file name Use Playwright & # 8217; s suggestedFilename () or suggested_filename belongings to maintain the original file name from the server: 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 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: 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: 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: 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: 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. 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. Tool Comparisons: On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.How to download a file using Playwright
Overview
Understanding File Downloads in Playwright
Setting Up Playwright Environment
1. Install Playwright
npm install playwright
pip install playwright
npx playwright install
playwright install
2. Verify Installation
npx playwright & # 8211; version
playwright & # 8211; version
3. Create a Browser Context with Download Support
const context = await browser.newContext ({acceptDownloads: true});context = await browser.new_context (accept_downloads=True)
How to Download a File in Playwright (JavaScript Example)
const {Cr} = require (& # 8216; playwright & # 8217;);
// 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 ();
await page.goto (& # 8216; https: //example.com/download & # 8217;);
const [download] = await Promise.all ([
page.waitForEvent (& # 8216; download & # 8217;), // Waits for the download to start
page.click (& # 8216; # downloadButton & # 8217;) // Triggers the download
]);
await download.saveAs (& # 8216; downloads/report.pdf & # 8217;);
console.log (& # 8216; File saved to: & # 8217;, await download.path ());
console.log (& # 8216; Suggested filename: & # 8217;, download.suggestedFilename ());
})();How to Download a File in Playwright (Python Example)
import asyncio
from playwright.async_api import async_playwright
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 ()
await page.goto (& # 8220; https: //example.com/download & # 8221;)
async with page.expect_download () as download_info:
await page.click (& # 8220; # downloadButton & # 8221;)
download = await download_info.value
await download.save_as (& # 8220; downloads/report.pdf & # 8221;)
mark (& # 8220; File saved to: & # 8221;, await download.path ())
print (& # 8220; Suggested filename: & # 8221;, download.suggested_filename)Handling Custom Download Paths
const circumstance = await browser.newContext ({
acceptDownloads: true,
downloadsPath: & # 8216; downloads/ & # 8217;
});context = await browser.new_context (
accept_downloads=True,
downloads_path= & # 8221; downloads/ & # 8221;
)await download.saveAs (& # 8216; custom-folder/myfile.pdf & # 8217;);
await download.save_as (& # 8216; custom-folder/myfile.pdf & # 8217;)
const filename = download.suggestedFilename ();
await download.saveAs (` downloads/ $ {filename} `);filename = download.suggested_filename
await download.save_as (f & # 8221; downloads/ {filename} & # 8221;)Validating the Downloaded File
Good Practices for File Download Automation
Enhance File Download Testing with BrowserStack Automate
Conclusion
Useful Resources for Playwright
Related Guides
Automate This With SUSA
Test Your App Autonomously