Playwright: How to Handle File Downloads Automatically

UNDETECTED LABS5 MIN READ
On this page

Playwright accepts downloads by default, but it puts them in a temporary folder under a random name and deletes that folder when the browser closes. So a script can click “Export”, finish without errors, and leave you with nothing. To keep the file you have to save it yourself.

There are two ways. You can give the browser a downloads folder at launch, which keeps every file but under random names. Or you can wrap the click in page.expect_download(), get a Download object back and save that file wherever and under whatever name you want. The second is what you’ll use most of the time.

Setup

Playwright 1.65 needs Python 3.10 or newer.

pip install playwright
playwright install chromium

Method 1: a downloads folder for the browser

downloads_path is an option of launch(), not of new_context(). Passing it to new_context() raises a TypeError.

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True,
            downloads_path='/tmp/downloads'
        )
        page = await browser.new_page()

        await page.goto('https://example.com/reports')
        await page.click('#download-csv')

        # Give the download time to complete
        await page.wait_for_timeout(3000)

        await browser.close()

asyncio.run(main())

The file stays in that folder after the browser closes, but under a name like 4e562b5b-a1cc-4c34-bbdb-7639b7233f9d, and the fixed pause is a guess at how long the download takes. Good enough for a one-off script, awkward for anything else.

Method 2: expect_download()

Put the action that starts the download inside page.expect_download(). When the download begins, Playwright hands you a Download object.

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(accept_downloads=True)
        page = await context.new_page()

        await page.goto('https://example.com/reports')

        # Wrap the click that triggers the download
        async with page.expect_download() as download_info:
            await page.click('#download-csv')

        download = await download_info.value

        # Save to a specific path
        await download.save_as('/tmp/downloads/report.csv')

        print(f'Downloaded: {download.suggested_filename}')
        print(f'Saved to: /tmp/downloads/report.csv')

        await browser.close()

asyncio.run(main())

download.suggested_filename is the name the browser picked, usually from the server’s Content-Disposition header or the link’s download attribute. download.url is where the file came from. await download.path() waits for the download to finish and returns the temporary file, which is gone once the browser closes.

Keeping the server’s filename

import asyncio
import os
from playwright.async_api import async_playwright

SAVE_DIR = '/tmp/downloads'

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(accept_downloads=True)
        page = await context.new_page()

        await page.goto('https://example.com/reports')

        async with page.expect_download() as download_info:
            await page.click('#download-csv')

        download = await download_info.value
        filename = download.suggested_filename
        save_path = os.path.join(SAVE_DIR, filename)

        await download.save_as(save_path)
        print(f'Saved: {save_path}')

        await browser.close()

asyncio.run(main())

Several files in a loop

For monthly reports, invoices or one export per account, click the buttons one after another and wait for each download:

import asyncio
import os
from playwright.async_api import async_playwright

SAVE_DIR = '/tmp/downloads'
os.makedirs(SAVE_DIR, exist_ok=True)

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(accept_downloads=True)
        page = await context.new_page()

        await page.goto('https://example.com/reports')

        # Get all download buttons on the page
        download_buttons = await page.locator('.download-btn').all()
        print(f'Found {len(download_buttons)} files to download')

        for i, button in enumerate(download_buttons):
            async with page.expect_download() as download_info:
                await button.click()

            download = await download_info.value
            filename = download.suggested_filename or f'file_{i+1}.csv'
            save_path = os.path.join(SAVE_DIR, filename)

            await download.save_as(save_path)
            print(f'[{i+1}/{len(download_buttons)}] Saved: {filename}')

        await browser.close()

asyncio.run(main())

Files behind a login

Log in with the same context first:

import asyncio
import os
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(accept_downloads=True)
        page = await context.new_page()

        # Log in first
        await page.goto('https://example.com/login')
        await page.fill('#email', 'your@email.com')
        await page.fill('#password', 'yourpassword')
        await page.click('#login-btn')
        await page.wait_for_url('**/dashboard')

        # Now download the protected file
        await page.goto('https://example.com/dashboard/exports')

        async with page.expect_download() as download_info:
            await page.click('#export-data')

        download = await download_info.value
        await download.save_as(f'/tmp/downloads/{download.suggested_filename}')

        print('Done')
        await browser.close()

asyncio.run(main())

The context keeps the session cookies, so the download request is logged in too.

Downloads that start on navigation

Sometimes the file URL itself starts the download, with no button. page.goto() on such a URL raises Download is starting, because no page ever loads. Catch that error inside the expect_download() block:

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(accept_downloads=True)
        page = await context.new_page()

        async with page.expect_download() as download_info:
            try:
                await page.goto('https://example.com/export/data.csv')
            except Exception:
                pass  # goto fails with "Download is starting"

        download = await download_info.value
        await download.save_as(f'/tmp/downloads/{download.suggested_filename}')

        await browser.close()

asyncio.run(main())

Large downloads and failures

save_as() waits until the download is complete, so the file is whole once it returns. failure() tells you whether the download broke:

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(accept_downloads=True)
        page = await context.new_page()

        await page.goto('https://example.com/reports')

        async with page.expect_download() as download_info:
            await page.click('#download-large-file')

        download = await download_info.value

        # save_as() waits for the download to complete before returning
        save_path = f'/tmp/downloads/{download.suggested_filename}'
        await download.save_as(save_path)

        # Check if the download failed
        failure = await download.failure()
        if failure:
            print(f'Download failed: {failure}')
        else:
            print(f'Saved to: {save_path}')

        await browser.close()

asyncio.run(main())

failure() returns None when the download succeeded and an error message when it didn’t. Check it on big files, where a dropped connection is more likely.

Public files without a browser

When the file URL is public and needs no cookies, you don’t need a browser at all. A plain HTTP client with httpx or requests starts in milliseconds and uses a fraction of the memory:

import httpx

def download_file(url: str, save_path: str):
    with httpx.stream('GET', url) as response:
        response.raise_for_status()
        with open(save_path, 'wb') as f:
            for chunk in response.iter_bytes(chunk_size=8192):
                f.write(chunk)
    print(f'Saved: {save_path}')

download_file('https://example.com/public/data.csv', '/tmp/data.csv')

Keep Playwright for files behind a login, files that JavaScript generates, and downloads behind a form or button. If only the login needs a browser, you can also copy its cookies into httpx with context.cookies() and fetch the files directly.

Example: all invoices from a billing portal

Log in once, then save every invoice PDF under the invoice’s own ID:

import asyncio
import os
from playwright.async_api import async_playwright

SAVE_DIR = '/tmp/invoices'
os.makedirs(SAVE_DIR, exist_ok=True)

async def download_invoices(email: str, password: str):
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(accept_downloads=True)
        page = await context.new_page()

        # Log in
        await page.goto('https://billing.example.com/login')
        await page.fill('[name="email"]', email)
        await page.fill('[name="password"]', password)
        await page.click('[type="submit"]')
        await page.wait_for_url('**/invoices')

        # Find all invoice download links
        invoice_links = await page.locator('a[data-type="invoice-pdf"]').all()
        print(f'Found {len(invoice_links)} invoices')

        for i, link in enumerate(invoice_links):
            invoice_id = await link.get_attribute('data-invoice-id')

            async with page.expect_download() as download_info:
                await link.click()

            download = await download_info.value
            filename = f'invoice_{invoice_id}.pdf'
            await download.save_as(os.path.join(SAVE_DIR, filename))
            print(f'[{i+1}/{len(invoice_links)}] {filename}')

        print(f'\nAll invoices saved to {SAVE_DIR}')
        await browser.close()

asyncio.run(download_invoices('your@email.com', 'yourpassword'))

Common problems

expect_download() times out. It waits 30 seconds for the download to start. If the server needs longer to prepare the file, raise it: page.expect_download(timeout=60000).

The file is empty or cut short. Something read it before the download finished. Read it only after await download.save_as(...) has returned.

The file has a meaningless name. The server sent no filename, so the browser made one up. Build the name yourself, from the URL or from data on the page, as in the invoice example.

Downloads work headed but not headless. The site probably detects headless browsers and serves them something else. Try Patchright or run headed under Xvfb.