File Download in Playwright

 

In Playwright Java, downloading a file involves listening for the Download event and then saving the file locally using the download.saveAs() method.

















How It Works:

  • Trigger the download action on the page (example: clicking a button or link).
  • Wait for the Download event using page.waitForDownload().
  • Save the file locally using the download.saveAs() method.

Example Use Case:

Download a sample file from https://file-examples.com/


Maven Dependency for Playwright

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.44.0</version> <!-- or latest -->
</dependency>




Java Code Example to Download File using Playwright


import com.microsoft.playwright.*;

import java.nio.file.Paths;

public class FileDownloadExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();

            Page page = context.newPage();

            // Navigate to the page that has download link/button
            page.navigate("https://file-examples.com/index.php/sample-documents-download/");

            // Click the first download link in the sample Word documents table
            Locator downloadLink = page.locator("a.btn:has-text('Download sample DOC file')");

            // Wait for the download to start and get the Download object
            Download download = page.waitForDownload(() -> {
                downloadLink.first().click(); // Trigger download
            });

            // Save the downloaded file to local path
            String downloadPath = "downloaded_file.doc";
            download.saveAs(Paths.get(downloadPath));

            System.out.println("File downloaded to: " + downloadPath);

            browser.close();
        }
    }
}



Output:


File downloaded to: downloaded_file.doc



Important Points:

  • waitForDownload() ensures Playwright listens for the download triggered by the action inside the callback.

  • You must call download.saveAs(Paths.get(...)) to save the file locally.

  • The file is stored in a temporary directory by default until saved manually.

No comments:

Post a Comment