Last updated on November 8th, 2025 at 10:33 am
Capturing screenshots is one of the most essential features in test automation. In this guide, you will learn how to capture screenshot in Playwright Java step by step. Whether you are debugging failed tests or creating visual evidence for test reports, screenshots make it easier to understand what went wrong during execution.
Playwright provides a powerful and flexible API to capture screenshots in different ways. You can take a snapshot of the visible page, the entire page, or even a specific element. This article will walk you through all these methods with clear Playwright Java screenshot examples, explain common options, and share best practices for organizing and managing screenshots effectively.
By the end of this tutorial, you will be able to confidently capture screenshots in Playwright Java for any use case, from debugging issues to creating visual documentation for your automation framework.
- What the Screenshots API Offers in Playwright Java
- How to Set Up Your Playwright Java Project for Screenshots
- How to Capture a Screenshot of the Visible Page
- How to Capture a Full-Page Screenshot in Playwright Java
- How to Capture a Screenshot of a Specific Element
- Handling Screenshot Failures and Errors in Playwright Java
- Best Practices for Screenshot in Playwright Java
- 1. Use Descriptive File Names
- 2. Organize Screenshots in Separate Folders
- 3. Capture Screenshots Only When Needed
- 4. Use Full Page Screenshots Wisely
- 5. Wait for Page and Elements to Load
- 6. Integrate Screenshots into Reports
- 7. Handle File Paths Dynamically
- 8. Combine Screenshots with Logging
- Example Tip for Reporting
- Screenshot Options and Advanced Features in Playwright Java
- What’s Next
- Conclusion
What the Screenshots API Offers in Playwright Java
The Playwright Java library provides a dedicated API to capture screenshots quickly and with flexibility. Whether you want a full-page image, a snapshot of the visible viewport, or a specific element capture, Playwright makes it simple to achieve all of these with just a few lines of code.
Screenshots can be captured at three main levels in Playwright Java:
- Page Screenshot – Captures the current visible part of the browser viewport.
- Full Page Screenshot – Captures the complete scrollable content of a web page.
- Element Screenshot – Captures only a specific element on the page, such as a button or a section.
Each of these options is useful for different testing scenarios. For instance, you might use a full-page screenshot in Playwright Java to verify entire layouts, while an element screenshot in Playwright Java is better for checking specific components.
Playwright also provides a set of configurable options through the Page.ScreenshotOptions and Locator.ScreenshotOptions classes. These options let you define the file path, image type (PNG or JPEG), image quality, and whether you want to capture the entire page or just the visible portion.
In the next section, you will learn how to set up your Playwright Java project and prepare it to take screenshots efficiently.
How to Set Up Your Playwright Java Project for Screenshots
Before you capture screenshots in Playwright, you need to ensure that your Playwright Java setup is ready. If you already have Playwright installed and configured with Eclipse and Maven, you can skip this step.

If you are new to Playwright or have not yet set up your environment, follow the complete step-by-step guide here:
Install Playwright Java – Setup with Eclipse and Maven
That guide covers:
- Installing Java and Maven
- Adding Playwright dependencies in
pom.xml - Setting up Eclipse for Playwright projects
- Running your first basic test
Once your setup is complete, you can easily launch a browser instance, create a new page, and start taking screenshots. Here’s a minimal example that initializes Playwright and opens a page:
import com.microsoft.playwright.*;
public class ScreenshotSetupExample {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
page.navigate("https://bing.com");
System.out.println("Playwright setup complete. Ready to capture screenshots!");
browser.close();
}
}
}With this setup ready, you can now proceed to capture different types of screenshots in Playwright Java.
How to Capture a Screenshot of the Visible Page
The most common way to capture a screenshot in Playwright Java is to take a snapshot of the visible part of the browser window. This method is simple and works well when you only need to capture what is currently visible on the screen.
You can use the page.screenshot() method for this purpose. The screenshot will be saved as an image file in your project directory based on the path you specify. Here is an example:
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class VisiblePageScreenshot {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
Page page = browser.newPage();
page.navigate("https://google.com");
// Capture visible page screenshot
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("visible-page.png")));
System.out.println("Visible page screenshot captured successfully!");
browser.close();
}
}
}Explanation of the Code
Playwright.create()initializes the Playwright instance.page.navigate("https://example.com")opens the target page.- The
page.screenshot()method captures the visible viewport and saves it as visible-page.png in your project’s root directory (the same folder where your.javafile or compiled class runs).

You can also provide a custom file path to store the screenshot in a specific location. For example:
.setPath(Paths.get("screenshots/homepage.png"))In this case, Playwright will save the screenshot inside a screenshots folder within your project directory. Make sure the folder exists before running the code to avoid path errors.
This approach is ideal for verifying layouts or capturing a snapshot at specific checkpoints during test execution.
If you are using testing frameworks like TestNG or JUnit, you can include this code inside your test method to automatically capture screenshots after certain actions or validations.
In the next section, you will learn how to capture a full-page screenshot in Playwright Java, which includes all scrollable content of the web page.
How to Capture a Full-Page Screenshot in Playwright Java
Sometimes you may need to capture the entire content of a web page, not just what is visible on the screen. In such cases, you can use the full page screenshot option in Playwright Java. This captures the entire scrollable area of the page, including sections that extend beyond the visible viewport.
To take a full page screenshot, you simply need to set the setFullPage(true) option in the Page.ScreenshotOptions class.
Here’s an example:
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class FullPageScreenshot {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
Page page = browser.newPage();
page.navigate("https://example.com");
// Capture full page screenshot
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("full-page.png"))
.setFullPage(true));
System.out.println("Full page screenshot captured successfully!");
browser.close();
}
}
}Explanation of the Code
- The
setFullPage(true)option tells Playwright to scroll through the entire page and capture all visible and hidden content. - The resulting image will include the complete web page from top to bottom.
- The screenshot will be saved as full-page.png in your project’s root directory unless you specify a different path.
For better organization, you can store all screenshots inside a dedicated folder, such as:
.setPath(Paths.get("screenshots/full-page-example.png"))When to Use Full Page Screenshots
Full page screenshots are especially helpful when:
- You are testing long, scrollable web pages like articles, product listings, or dashboards.
- You need visual proof of complete layout coverage for UI testing.
- You want to compare UI changes between different test runs or deployments.
However, full page screenshots can increase file size and take slightly longer to capture, especially on pages with heavy media or dynamic content. Use them when you need a complete visual reference of the entire page.
In the next section, you will learn how to capture a screenshot of a specific element in Playwright Java, which is useful when you only want to test or verify a particular part of the page.
How to Capture a Screenshot of a Specific Element
Sometimes, you don’t need the entire page screenshot. Instead, you might want to capture only a specific element, such as a button, image, form section, or product card. In Playwright Java, you can easily do this using the locator feature combined with the .screenshot() method.
Capturing an element screenshot helps you focus on a particular UI component and is especially useful when you want to validate element styling, placement, or content during automated testing.
Here’s an example:
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class ElementScreenshot {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
Page page = browser.newPage();
page.navigate("https://www.wikipedia.org/");
// Locate the element you want to capture
Locator element = page.locator(".central-textlogo");
// Capture element screenshot
element.screenshot(new Locator.ScreenshotOptions()
.setPath(Paths.get("element-screenshot.png")));
System.out.println("Element screenshot captured successfully!");
browser.close();
}
}
}Explanation of the Code
page.locator("h1")locates the<h1>element on the page. You can replace the selector with any CSS, XPath, or text-based locator as needed.- The
element.screenshot()method captures only that specific element and saves it as element-screenshot.png in your project’s root directory. - You can specify a custom path, such as
screenshots/header.pngif you want to store it in a separate folder.

When to Use Element Screenshots
Element screenshots are beneficial when:
- You are testing UI components individually, such as buttons, forms, or banners.
- You want to verify that a particular section renders correctly after a UI update.
- You are performing visual regression testing on specific components rather than the entire page.
Capturing only the required element also reduces image size and processing time compared to full-page screenshots.
In the next section, you will learn how to handle screenshot failures and errors in Playwright Java, and how to automatically capture screenshots when a test fails.
Handling Screenshot Failures and Errors in Playwright Java
When working with automated tests, screenshots are most valuable when something goes wrong. Playwright Java allows you to handle screenshot failures gracefully and even capture screenshots automatically whenever a test fails.
Sometimes, screenshot capture might fail due to issues like:
- Invalid or missing file path
- Page or element not fully loaded before capture
- Browser or context already closed
- Insufficient file permissions
To avoid these issues, you should always handle exceptions properly and ensure the path exists before saving a screenshot.
Here’s an example of safely handling screenshot capture with error handling:
package com.example.test;
import com.microsoft.playwright.*;
import java.nio.file.Files;
import java.nio.file.Paths;
public class SafeScreenshotExample {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
Page page = browser.newPage();
page.navigate("https://www.wikipedia.org/");
// Safely capture screenshot with error handling
try {
Files.createDirectories(Paths.get("screenshots"));
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshots/safe-screenshot.png")));
System.out.println("Screenshot captured successfully!");
} catch (Exception e) {
System.out.println("Failed to capture screenshot: " + e.getMessage());
}
browser.close();
}
}
}Capture Screenshot on Test Failure (Using TestNG)
If you are running Playwright Java tests with TestNG, you can automatically capture screenshots when a test fails. This approach is extremely useful for debugging and reporting.
Here’s an example of capturing screenshots on failure using a TestNG listener:
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class ScreenshotOnFailureListener implements ITestListener {
@Override
public void onTestFailure(ITestResult result) {
Object testClass = result.getInstance();
Page page = ((BaseTest) testClass).getPage();
try {
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("screenshots/" + result.getName() + "-failed.png")));
System.out.println("Captured screenshot for failed test: " + result.getName());
} catch (Exception e) {
System.out.println("Error capturing failure screenshot: " + e.getMessage());
}
}
}Tip: To use this listener, register it in your
testng.xmlor annotate your test class with@Listeners(ScreenshotOnFailureListener.class).
Common Reasons for Screenshot Failures
- File path not found – The directory must exist before saving the screenshot.
- Closed context – Ensure the browser or page is still open when capturing.
- Dynamic elements – Wait for elements to load before taking a screenshot.
- Parallel test conflicts – Use unique names for screenshots to avoid overwriting.
By handling errors and automating screenshots on failure, you can quickly identify UI or functionality issues without re-running the test manually.
In the next section, you will learn the best practices for capturing screenshots in Playwright Java, including file organization, naming conventions, and performance tips.
Best Practices for Screenshot in Playwright Java
Capturing screenshots in Playwright Java is simple, but following a few best practices can make your process more reliable, organized, and maintainable. These tips help you manage screenshots efficiently in large automation frameworks and improve the overall readability of your reports.
1. Use Descriptive File Names
Instead of generic names like screenshot.png, use meaningful and unique file names. Include details such as test name, page name, or timestamp.
Example:
.setPath(Paths.get("screenshots/loginPage_" + System.currentTimeMillis() + ".png"))This ensures each screenshot is easy to identify and prevents overwriting old files.
2. Organize Screenshots in Separate Folders
Keep your screenshots structured by test type or module. Create folders like screenshots/homepage, screenshots/login, or screenshots/errors. This improves navigation and helps when sharing reports.
3. Capture Screenshots Only When Needed
Avoid taking unnecessary screenshots during every test step, as this increases execution time and storage use. Capture screenshots only for important validations, UI checks, or failed tests.
4. Use Full Page Screenshots Wisely
While full-page screenshots are useful for visual validation, they can create large image files. Use them only when the complete layout verification is required. For most checks, capturing the visible area or specific elements is sufficient.
5. Wait for Page and Elements to Load
Always ensure that the page and target elements are fully loaded before capturing screenshots. Use appropriate waits like page.waitForSelector() to prevent blank or incomplete captures.
6. Integrate Screenshots into Reports
Attach screenshots to your test reports for better traceability. If you are using TestNG or JUnit, integrate screenshots in your test reports to make debugging faster and more visual.
7. Handle File Paths Dynamically
When running tests across different environments, use dynamic file paths. This ensures your screenshot directories work on all operating systems.
8. Combine Screenshots with Logging
Log the screenshot path along with test results. This helps you quickly locate the image file when analyzing failures or reviewing logs.
Example Tip for Reporting
If you are creating custom HTML reports, you can embed the screenshot path like this:
<img src="screenshots/login-failure.png" alt="Playwright Java Screenshot Example" width="400">Following these best practices will make your screenshot management clean, consistent, and more scalable, especially in large automation frameworks.
In the next section, you will explore the advanced screenshot options available in Playwright Java, such as controlling image format, clipping specific areas, and masking sensitive information.
Screenshot Options and Advanced Features in Playwright Java
Playwright provides several flexible options when capturing screenshots. These options help you customize the output, control quality, choose image format, and even mask sensitive data before saving the file.
Below are some of the most commonly used options in Playwright Java:
Full Page Screenshot
You can capture the entire scrollable page using the setFullPage(true) option.
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("screenshots/fullpage.png"))
.setFullPage(true));Tip: This is especially useful for long pages that extend beyond the visible screen area.
Specify Image Format (PNG or JPEG)
By default, Playwright captures screenshots in PNG format. However, you can change it to JPEG and even adjust the image quality.
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("screenshots/page.jpg"))
.setType(ScreenshotType.JPEG)
.setQuality(80));setType(ScreenshotType.JPEG)– saves image as JPEG.setQuality(80)– sets image compression quality (valid for JPEG only).
Hide or Mask Sensitive Elements
Sometimes you may not want to show certain elements, such as personal data or ads. You can hide or mask them before taking a screenshot.
// Create list of locators to mask
Locator creditCardField = page.locator("#credit-card");
Locator emailField = page.locator("#email");
List<Locator> maskElements = Arrays.asList(creditCardField, emailField);
// Safely capture screenshot with error handling
try {
Files.createDirectories(Paths.get("screenshots"));
// Take masked screenshot
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshots/masked.png"))
.setMask(maskElements));
System.out.println("Screenshot captured successfully!");
} catch (Exception e) {
System.out.println("Failed to capture screenshot: " + e.getMessage());
}Result: The specified elements will be blurred or hidden in the final screenshot.
Capture Screenshot of a Specific Area
If you only need a portion of the page, use the setClip() option to define coordinates.
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("screenshots/area-screenshot.png"))
.setClip(0, 0, 800, 400)); // x, y, width, heightThis captures only the defined rectangular area (x, y, width, height).
Save Screenshot with Custom Path
You can store screenshots in organized folders for better test reporting.
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("reports/screenshots/homepage.png")));This helps maintain clarity when running multiple test suites.
Automatic Screenshot on Failure
In a TestNG or JUnit setup, you can configure Playwright to automatically capture screenshots whenever a test fails.
This is often done by adding screenshot logic inside your @AfterMethod block (covered in your Playwright + TestNG integration articles).
You can explore detailed integration steps in our Playwright with TestNG tutorial.
Summary
Playwright Java gives you complete control over screenshots, from full-page captures to element masking and advanced formatting.
These features help create visual evidence for every test run, ensuring faster debugging and professional reporting.
What’s Next
Now that you have learned how to capture screenshots in Playwright Java, the next step is to explore how to record videos of your test executions.
Read this complete guide:
How to Record Test Videos in Playwright Java
This article explains how to enable video recording for your Playwright tests, helping you debug test failures more effectively by reviewing real execution footage.
Conclusion
In this guide, you learned how to capture screenshots in Playwright Java using different methods such as visible page, full page, and element-level screenshots. You also explored how to handle failures with automatic screenshots and applied best practices for better test reporting.
Capturing screenshots is an essential part of modern test automation. It helps you identify UI issues quickly, debug failed scenarios, and maintain visual accuracy across browsers.
By integrating screenshot capture in Playwright Java into your automation framework, you can make your testing process more reliable and professional. Start applying these techniques in your next Playwright Java project to enhance the quality and visibility of your test results.