Download File in Playwright Java

Profile picture for user arilio666

This article will discuss how we can download files and play around with the download method present in playwright java.

Playwright can also download a file and save it to a default path. Download objects are dispatched via page.on('download') event. The download files that belong to the browser context are deleted when the context is closed. We can see that the download event is set on course once it starts, and the path is available when it gets completed.

Example:

For example, this site will be used explicitly for download examples where when licked on the download button, it saves a file to our local path.

    public static void main(String[] args) {

        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
        Page page = browser.newPage();
        page.navigate("http://demo.automationtesting.in/FileDownload.html");
        Download waitForDownload = page.waitForDownload(() -> {

            page.locator("//a[@type='button']").click();

        });

        System.out.println(waitForDownload.url());
        System.out.println(waitForDownload.page().title());
        System.out.println(waitForDownload.path().toString());

    }
}

So here, we used the playwright's very own waitForDownload method and stored it in a variable.
Inside this method, we found the locator for the download button from the site and placed it.

waitForDownload.url() - This will fetch the URL of the download page.
waitForDownload.page().Title () - This will fetch the title of the download page.
waitForDownload.path().toString() - This will fetch the path where the file has been downloaded on our local machine.

waitForDownload.saveAs() - Use this to save the files to our required path.
waitForDownload.cancel() - This will cancel the download when clicked.
waitForDownload.failure() - Returns download error.
waitForDownload.delete() - This will delete the downloaded file.