Take Screenshot in Playwright Java

Profile picture for user arilio666

This article will show how we can take Screenshots in playwright java.

1.) Screenshot

Here is a quick and easy way to take a Screenshot and save it in a file.

        Playwright playwright = Playwright.create();
        Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
        Page page = browser.newPage();
        page.navigate("http://autopract.com/selenium/upload1/");
        page.setInputFiles("//input[@type='file']",
                Paths.get("C:\\Users\\arili\\git\\Assignments\\Selenium\\target\\CRED.xlsx"));
        page.screenshot(new Page.ScreenshotOptions()
                .setPath(Paths.get("C:\\Users\\arili\\git\\Assignments\\Selenium\\target\\uploadPage.png")));
                

This is a simple upload code; at the end, we are screenshotting and saving it to the target folder.

We can see that the image file has been saved to the provided path.
The screenshot API accepts many parameters for image format, clip area, quality, etc.

2.) Full Page Screenshot

We can also take a screenshot of the full page using this:

page.screenshot(new Page.ScreenshotOptions()
 .setPath(Paths.get("C:\\Users\\arili\\git\\Assignments\\Selenium\\target\\uploadPage.png"))
 .setFullPage(true));
 

Using the same method, we can screenshot the entire full page.

3.) Buffer Capture

Rather than writing to a file, we can capture the Screenshot into a buffer and use it or post-process it to a third-party pixel diff facility.

byte[] buffer = page.screenshot();
System.out.println(Base64.getEncoder().encode(buffer));

4.) Screenshot Element

We can also capture Screenshots of specific Elements.

page.locator(".class").screenshot(new Locator.ScreenshotOptions().setPath(Paths.get("C:\\Users\\arili\\git\\Assignments\\Selenium\\target\\uploadPage.png")));