Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Playwright: File Upload, Download, and Screenshots

Learn how to automate file uploads, downloads, and screenshots in Python Playwright. Covers set_input_files, file chooser events, expect_download, and screenshot modes with code examples.

~5 min readPython
#Playwright#File Upload#File Download#Screenshots
Illustration of a browser window with an upload arrow, a download arrow, and a camera icon representing Playwright's file upload, download, and screenshot capabilities.

File upload, download, and screenshot automation in Python Playwright requires understanding the browser events and APIs behind each operation. Uploads may involve existing <input type='file'> elements or OS-level file chooser dialogs. Downloads are exposed as events that you can save to disk. Screenshots require choosing between viewport, full-page, and element capture. This article covers the practical implementation of all three operations using Playwright's Python API, with examples you can adapt to test or scraping scripts.

Why File Operations Need Special Handling in Playwright

Playwright runs in the browser context and cannot interact with native OS dialogs directly. When a user clicks a button that opens a file picker, the browser triggers a file chooser event. Playwright intercepts this event and lets you provide file paths programmatically. Similarly, downloads are initiated by the browser but are exposed as events so you can control where the file is saved. Screenshots are a direct browser API and are simpler to implement, but you still need to choose the right capture mode for your use case.

Setting Up Playwright for File Upload and Download

Create the browser context with download support enabled so your script can receive download events. In Playwright, a context accepts downloads when accept_downloads=True; setting it explicitly makes behavior consistent across versions and configurations.

python
from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch(headless=False) context = browser.new_context(accept_downloads=True) page = context.new_page() # your automation code here browser.close()

If you use the async API, the pattern is similar with async with and await on each call. The accept_downloads flag matters because download events are only generated when the context is configured to accept downloads.

Uploading Files with set_input_files

The most straightforward upload scenario is when the page contains an <input type='file'> element. Playwright's set_input_files method sets the file paths directly on the input, bypassing the file chooser entirely. This works for single or multiple files.

python
page.goto('https://example.com/upload') page.set_input_files('#file-input', 'report.pdf') # For multiple files: page.set_input_files('#file-input', ['report.pdf', 'data.csv'])

You can also pass file content as bytes instead of paths, which is useful when the file is generated in memory:

python
file_content = b'name,age\nAlice,30\nBob,25' page.set_input_files('#file-input', {'name': 'data.csv', 'mimeType': 'text/csv', 'buffer': file_content})

set_input_files performs Playwright's usual actionability waits before setting the value. After setting the files, you can submit the form or trigger the upload as the application requires.

Handling File Chooser Dialogs

When the upload is triggered by clicking a button that opens a native file picker, use expect_file_chooser. This context manager waits for the file chooser event and gives you a FileChooser object to set files on.

python
with page.expect_file_chooser() as fc_info: page.click('#upload-button') file_chooser = fc_info.value file_chooser.set_files('image.png')

The set_files method on the file chooser accepts the same inputs as set_input_files: a single path, a list of paths, or a dictionary with buffer. This pattern is essential for uploads that do not use a plain input element, such as drag-and-drop zones that trigger a file picker on click.

Downloading Files with expect_download

Downloads are handled with expect_download, which waits for a download event after an action. The resulting Download object provides methods to access the suggested filename and save the file to a local path.

python
with page.expect_download() as download_info: page.click('#download-button') download = download_info.value print(download.suggested_filename) download.save_as('/path/to/save/' + download.suggested_filename)

The save_as method writes the file to the specified location. If you only need the file's temporary path, call download.path(), which returns the path where Playwright has stored the file in its temporary directory. This is useful if you want to read the content without saving it permanently.

python
with page.expect_download() as download_info: page.click('#download-button') download = download_info.value file_path = download.path() with open(file_path, 'rb') as f: content = f.read()

download.path() blocks until the download completes, so you do not need to add an extra wait. If the download fails or takes too long, it raises a timeout error.

Taking Screenshots with page.screenshot

Playwright's page.screenshot captures the visible viewport by default. To capture the full scrollable page, pass full_page=True. You can also capture a specific element using locator.screenshot().

python
# Full page screenshot page.screenshot(path='full_page.png', full_page=True) # Element screenshot page.locator('.header').screenshot(path='header.png') # Screenshot with custom clip page.screenshot(path='clip.png', clip={'x': 0, 'y': 0, 'width': 500, 'height': 500})

The default format is PNG, but you can use JPEG by specifying type='jpeg' and adjusting the quality parameter (0-100). For large pages, full-page screenshots can be memory-intensive; consider capturing only the needed region or using JPEG with lower quality to reduce file size.

Waiting for Downloads and Managing Timeouts

expect_download accepts a timeout parameter in milliseconds. If the download event does not occur within that window, a TimeoutError is raised. This is useful when the download is triggered only after some asynchronous action.

python
with page.expect_download(timeout=10000) as download_info: page.click('#slow-download')

The timeout applies only to waiting for the download event, not to the time needed for the file itself to finish downloading. After the event fires, download.path() and download.save_as() block until the file is fully written. For slow downloads, account for that extra time or run the save in a separate task; do not rely on the expect_download timeout to bound the entire operation.

Common Pitfalls and Edge Cases

One common issue is that set_input_files does not work on elements that are not <input type='file'>. For custom upload widgets, always use the file chooser approach. Another pitfall is forgetting to configure the context to accept downloads; without a context that accepts downloads, expect_download times out. In headless mode, downloads work the same way. If you need a predictable location, pass an absolute path to save_as rather than relying on the current working directory.

When handling multiple downloads, each expect_download context must be paired with the action that triggers that specific download. If a button can trigger more than one download, use a predicate to select the expected download or use page.on('download') to listen for all download events. The latter is more flexible but requires manual event handling.

Screenshots can also fail if the page is not fully loaded or if the element is not in the viewport. Playwright automatically scrolls elements into view for element screenshots, but for full-page screenshots, ensure the page has settled (for example, after network idle) to avoid capturing incomplete content.

Finally, remember that file paths in set_input_files and save_as are resolved relative to the current working directory. For robust scripts, use absolute paths or construct paths with os.path.join to avoid platform-specific separator issues.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.