October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
browser automation

How to Download Files with Browser Automation (Playwright, Selenium and Puppeteer)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I download a file with browser automation? Treat the click and the byte transfer as two separate jobs. In Playwright, register a download wait before clicking, await the resulting Download object, and call saveAs() to copy the file into a directory your application owns. If the final URL and authentication context are already known, an HTTP client can be simpler: use the browser to discover the link or cookies, then fetch the response directly. Selenium’s own guidance recommends that pattern because its API does not expose download progress.

Choose the transfer method first

Use browser automation when a user interaction is required: a menu must open, JavaScript must create a URL, a consent step must be accepted, or an authenticated session is needed. Use a direct HTTP request when you already know the file URL and can safely reproduce the required cookies, headers or authorization. The latter is usually easier to validate, retry and stream, but never send session credentials to an unintended origin.

  • Browser-controlled download: useful for interaction-heavy flows and sites that generate files only after a click.
  • HTTP download after discovery: use Selenium (or another browser) to locate the link and session context, then curl or an HTTP library to retrieve the bytes.
  • Verification: wait for a completion signal such as a saved file or completed response; do not guess with a fixed sleep.

Playwright: wait before clicking, then save

Playwright has a first-class download event. The listener must be created before the action that starts the transfer, otherwise a very fast download can be missed.

import { chromium } from 'playwright';
import path from 'node:path';
import fs from 'node:fs/promises';

const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
const destinationDir = path.resolve('artifacts');
await fs.mkdir(destinationDir, { recursive: true });

try {
  await page.goto('https://example.com/files', { waitUntil: 'domcontentloaded' });
  const downloadPromise = page.waitForEvent('download');
  await page.getByRole('link', { name: /download file/i }).click();
  const download = await downloadPromise;
  const suggested = download.suggestedFilename();
  // Validate or replace this name before using it in a filesystem path.
  const safeName = suggested.replace(/[^a-zA-Z0-9._-]/g, '_');
  const destination = path.join(destinationDir, safeName);
  await download.saveAs(destination);
  console.log(`Saved ${destination}`);
} finally {
  await browser.close();
}

saveAs() is the persistence step: it waits as necessary and copies the completed download to your chosen path. You can also call download.path() to obtain a temporary path, although Playwright documents that path() throws when the browser is connected remotely. The suggested filename generally comes from the response’s Content-Disposition header or an HTML download attribute. Different browsers can compute it differently, so regard it as a hint rather than a portable guarantee.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Keep the file after the context closes

Attachment downloads normally go to a temporary directory and are deleted when the producing browser context closes. Always complete saveAs() (or move the file to durable storage) before closing that context. Playwright also provides a downloadsPath browser-launch option when you need a configured download directory, but application-owned per-job paths make collisions and cleanup easier to control.

Useful Playwright checks

  • Call download.failure() when you need to distinguish a canceled or failed transfer.
  • Use a unique directory or filename for each job; do not let an untrusted suggested name escape that directory with ../ segments.
  • After saving, check the extension, MIME signature and expected size or checksum for the file type your application requires.
  • Apply a finite test or job deadline and delete partial artifacts on failure.

Selenium: discover in the browser, fetch with HTTP

Selenium’s official documentation says that although a browser under Selenium control can start a download, its API does not expose download progress, making it less suitable for tests that must verify downloaded files. Its documented approach is to locate the link and obtain any required cookies with Selenium, then use an HTTP library such as curl to retrieve the file. This gives the transfer code direct access to status, headers, streaming and retries.

from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
from pathlib import Path
from urllib.parse import urljoin

options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
try:
    driver.get("https://example.com/files")
    link = driver.find_element(By.CSS_SELECTOR, "a.download")
    file_url = urljoin(driver.current_url, link.get_attribute("href"))
    selenium_cookies = driver.get_cookies()
    cookies = {c["name"]: c["value"] for c in selenium_cookies}
    with requests.get(file_url, cookies=cookies, stream=True, timeout=90) as response:
        response.raise_for_status()
        target = Path("artifacts/result.bin")
        target.parent.mkdir(parents=True, exist_ok=True)
        with target.open("wb") as output:
            for chunk in response.iter_content(chunk_size=1024 * 1024):
                if chunk:
                    output.write(chunk)
finally:
    driver.quit()

Copy only the cookies needed for the intended host and scope. Some applications also require an Authorization header, CSRF token or a browser-generated URL; obtain those values in the page and reproduce them narrowly in the HTTP request. Check the response’s content type and length before accepting it as the expected file. Selenium’s documentation mentions HtmlUnit’s AttachmentHandler as a driver-specific alternative; do not assume that behavior applies to every driver.

Rank #2
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
  • Easily store and access 5TB of content on the go with the Seagate portable drive, a USB external hard Drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Puppeteer: do not copy Playwright’s download API

The current Puppeteer Files guide (version 25.12.0 in the surfaced documentation) states: “Currently, Puppeteer does not offer a way to handle file downloads in a programmatic way.” Therefore, page.waitForEvent('download') and the Playwright Download object are not Puppeteer APIs. If Puppeteer is required, consult the exact version’s official documentation for the browser/protocol mechanism it supports, or use the same browser-discovery-plus-HTTP pattern described for Selenium. Pin the Puppeteer version in your project and verify the selected mechanism against that version before relying on it.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to know a download really finished

  1. Register the framework’s event or begin the controlled HTTP request before triggering the action.
  2. Await the framework operation that represents completion: Playwright’s saveAs() or path(), or the HTTP response stream reaching end-of-file.
  3. Handle cancellation, timeout and non-success HTTP status as failures, not as empty successful files.
  4. Validate the result: inspect magic bytes or a parser, compare an expected checksum when available, and reject an HTML error page saved with a .pdf or .zip suffix.
  5. Close the context only after durable persistence, then remove temporary and partial files according to your retention policy.

A fixed delay can pass on a fast machine and fail on a slow network. Completion signals remain meaningful when transfer time varies.

Framework comparison

Framework or approach Completion primitive Persistence and cleanup Important limitation
Playwright page.waitForEvent('download'), then saveAs() or path() Context downloads are temporary; copy before context close path() is unavailable when connected remotely
Selenium Separate HTTP client’s response and stream Your HTTP code controls destination, retries and validation Selenium API does not expose download progress
Puppeteer No portable first-class programmatic download API in the cited Files guide Depends on the version-specific browser/protocol method selected Do not transplant Playwright event examples
Direct HTTP HTTP status plus completed stream and validation Explicit path, timeout, retry and checksum policy Cannot replace interactions or browser-only authorization automatically

Common failures and fixes

The script hangs waiting for a download

The click may open a new tab, submit a form, or generate an in-page response instead of emitting a download. Confirm the locator targets the actual control, wait for the relevant popup or navigation when appropriate, and inspect network behavior. In Playwright, create the download promise immediately before the click.

Rank #3
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
  • Easily store and access 1TB to content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop. Reformatting may be required for Mac
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

The event is missed

Starting the listener after clicking is a race. Create page.waitForEvent('download') first and then trigger the action.

The file disappears

You retained only Playwright’s temporary path and closed the context. Await saveAs() to an application-owned destination before cleanup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The saved file is an HTML error page

Authentication expired, a redirect reached a login page, or the server returned an application error with status 200. Check status, final URL, content type and file signature; refresh the session or reproduce required headers.

Rank #4
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
  • Easily store and access 4TB of content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Names collide or escape the work directory

Suggested names are untrusted input. Normalize them, reject path separators and parent-directory components, and allocate a unique per-job directory.

Remote execution cannot read the path

A path inside a remote browser machine is not necessarily visible to your test runner. Use a supported transfer mechanism, such as saving through the framework’s remote-capable API or streaming the file through your own HTTP layer; Playwright specifically documents the remote limitation for path().

Large files exhaust memory

Stream HTTP responses in chunks, avoid converting the entire file to a buffer, and enforce maximum size and deadline limits. For browser downloads, persist directly with saveAs() and monitor available disk space.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
UnionSine 500GB Ultra Slim Portable External Hard Drive HDD-USB 3.0
  • [Upgraded Version] - This external hard drive features a mirrored logo stripe combined with a striped anti-slip design, and the rounded corners of the casing make it easier to grip. The stripes also have a heat dissipation function, ensuring stable and fast data transfer.
  • 【Ultra-thin and quiet】 - The motherboard adopts JMicron 578 noise-free solution, giving you a quiet working environment. Lightweight and portable size designed to fit in your pocket for easy portability.
  • 【Ultra-Fast Data Transfers】 - Pairing this external hard drive with JMicron 578 solution USB 3.0 and USB 2.0 interfaces enables blazing-fast data transfer. It boasts theoretical read speeds of up to 125MB/s and write speeds of up to 103MB/s.
  • 【Plug and Play】 - With no software to install, just plug it in and the drive is ready to use.The hard disk chip is wrapped with an aluminum anti-interference layer to increase heat dissipation and protect data.
  • 【What You Get】 - 1 x Portable Hard Drive, 1 x USB 3.0 Cable, 1 x User Manual, Gift-type shell packaging ,Three-year manufacturer's warranty and free technical support services.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean image or PDF of a web page rather than an attachment generated by a user workflow, ScreenshotNeo provides a single HTTP call. It accepts consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server lets Claude, Cursor and other MCP clients call take_screenshot, get_page_info and capture_pdf.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for options such as PNG, JPEG or WebP output, full-page lazy-image loading, CSS-selector element capture, device and retina settings, custom CSS or JavaScript, waits, request blocking, headers, cookies, geolocation, signed links, asynchronous jobs and bulk capture. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Operational checklist

  • Use a stable locator and trigger the action only after the page is ready.
  • Install the completion wait before the action.
  • Give every job a unique, controlled destination.
  • Keep credentials scoped to the intended origin.
  • Set finite timeouts, stream large responses and clean partial files.
  • Validate status, type, size and (where possible) cryptographic integrity.
  • Record enough metadata—URL, final URL, filename, duration and failure reason—to diagnose jobs without logging secrets.

Frequently Asked Questions

Can I use a browser download directory as proof that a file is complete?

Not by itself. Directory polling can observe temporary names and partial files. Prefer Playwright’s awaited save operation or an HTTP response stream that has ended, followed by content validation.

Should I trust Content-Disposition filenames?

Use them as suggestions only. Sanitize separators and control characters, enforce an allowed extension policy, and generate your own collision-resistant name when the source is untrusted.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What changes when the browser runs in a container?

The browser’s filesystem and the test runner’s filesystem may be different. Mount an intentional artifact directory or transfer the bytes through a supported API, and test cleanup separately from local execution.

Quick Recap

SaleBestseller No. 1
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.99
Bestseller No. 2
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
Seagate Portable 5TB External Hard Drive HDD – USB 3.0 for PC, Mac, PS4, & Xbox - 1-Year Rescue Service (STGX5000400), Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$229.99
Bestseller No. 3
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.80
Bestseller No. 4
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
Seagate Portable 4TB External Hard Drive HDD – USB 3.0, 1-Year Rescue
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$151.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.