How do I handle file uploads and downloads with Playwright?

Playwright provides APIs for handling file uploads and downloads in both Python and JavaScript.

Here is how you can do it in both languages:

Python:

Handling file uploads:

You can use the set_input_files() method to upload files.

# Import necessary packages
from playwright.sync_api import sync_playwright

# Open a new browser instance
with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()

    # Navigate to the file upload page
    page.goto('https://your-website.com/upload')

    # Upload the file
    page.set_input_files('input[type="file"]', 'path/to/your/file')

    # Close the browser
    browser.close()

Handling file downloads:

Playwright makes it easy to handle file downloads using the page.on("download") method and the download.path() method.

# Import necessary packages
from playwright.sync_api import sync_playwright

# Open a new browser instance
with sync_playwright() as p:

    browser = p.chromium.launch()
    page = browser.new_page()

    # Navigate to the download page
    page.goto('https://your-website.com/download')

    # Set up download listener
    download_promise = page.expect_download()

    # Perform download action
    page.click('a#download')

    # Get download object
    download = download_promise.result()

    # Get downloaded file path
    path = download.path()

    # Close the browser
    browser.close()

JavaScript:

Handling file uploads:

To handle file uploads in JavaScript, you can use the setInputFiles() method.

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();

    await page.goto('https://your-website.com/upload');

    // Upload the file
    await page.setInputFiles('input[type="file"]', '/path/to/your/file');

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

Handling file downloads:

Playwright provides the page.on('download') event to handle file downloads in JavaScript.

const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();

    await page.goto('https://your-website.com/download');

    // Set up download listener
    const [download] = await Promise.all([
        page.waitForEvent('download'),
        page.click('a#download')
    ]);

    // Get downloaded file path
    const path = await download.path();

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

Note: Make sure the file path for uploading or downloading files is correct, otherwise you may encounter errors.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon