Purpose
- When performing website testing, validating file upload functionality is crucial as users need to upload documents and images, such as in job portals, eCommerce websites, cloud storage systems, and others.
- Automating this process ensures reliability and efficiency in testing these functionalities, and automated testing tools like Selenium provide effective solutions for this task. In this blog, we delve into how to handle file upload in Playwright , exploring techniques to handle file upload and automate file upload functionality.
Playwright – File Download
- Download objects are dispatched by page via the Page.onDownload(handler) event.
- All the downloaded files belonging to the browser context are deleted when the browser context is closed.
- Download event is emitted once the download starts. Download path becomes available once download completes.
Playwright Method to File Download
/ Wait for the download to start
Download download = page.waitForDownload(() -> {
// Perform the action that initiates download
page.locator("(//a[contains(@class,'flex items-center')])[1]").click();
});
// Wait for the download process to complete and save the downloaded file somewhere
download.saveAs(Paths.get("/path/to/save/at/", download.suggestedFilename()));
Example ::
package com.example;
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class FileDownload {
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("https://getsamplefiles.com/sample-audio-files/m4r");
// page.waitForURL("/formats/doc",new Page.WaitForURLOptions().setTimeout(6000));
page.goBack();
page.goForward();
Download fielDownload = page.waitForDownload(()->{
page.locator("(//a[contains(@class,'flex items-center')])[1]").click();
});
// download cancel
// fielDownload.cancel();
// print download location - default download in your system
System.out.println(fielDownload.path().toString());
// Save the File specified location
fielDownload.saveAs(Paths.get("fileDownload.zip"));
}
}
Comments
Post a Comment