October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Java

How to Take Screenshots with Playwright in Java

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Playwright for Java, save a page screenshot with page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png"))). Add .setFullPage(true) to capture the full scrollable page, or call locator.screenshot(...) to capture one element. The API can also return image bytes instead of writing a file, and Playwright Test provides screenshot assertions for visual regression checks.

Set up a page and save a screenshot

The examples below assume you have already created a Playwright Page and navigated to the page you want to capture. This is the core Java API call:

import java.nio.file.Paths;
import com.microsoft.playwright.Page;

page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("screenshot.png")));

The screenshot is written to the path supplied to setPath. Use a path appropriate to your project, and make sure the process can write to its parent directory. The Java API examples use java.nio.file.Paths. For version-specific option names and availability, check the Playwright Java screenshots guide and current Page API reference.

Return image bytes instead of saving a file

Omit the path to receive the screenshot as a byte array. This is useful when a test or service will encode, upload, or compare the image without first saving it locally.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
byte[] buffer = page.screenshot();

You can pass buffer to your own Base64 encoder, image-processing code, or pixel-diff system. The API returns image data; what you do with it is up to the application.

Capture the full scrollable page

By default, a page screenshot covers the visible viewport. Set fullPage to true to capture the full scrollable page, as if it were displayed on a very tall screen:

page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("full-page.png"))
    .setFullPage(true));

This changes the capture extent; it does not select a specific element. For a particular region, use a clip rectangle; for a component, use a locator screenshot.

Screenshot a single element

Use Locator.screenshot when the target is one matched element rather than the whole page. For example:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import com.microsoft.playwright.Locator;

page.locator(".header").screenshot(
    new Locator.ScreenshotOptions()
        .setPath(Paths.get("header.png")));

A CSS selector is convenient when the page has a stable class or test attribute. You can also use a role-based locator, which expresses what the element is rather than how it is styled:

page.getByRole(AriaRole.BANNER).screenshot(
    new Locator.ScreenshotOptions()
        .setPath(Paths.get("banner.png")));

Use a locator that identifies one intended element reliably. If the locator matches nothing or resolves ambiguously, fix the selector or wait for the page state your application requires before capturing. Locator screenshot options also support masking selected regions and controlling animations.

Choose screenshot options for the output you need

Page and locator screenshot options let you control image format, dimensions, appearance, and capture stability. Confirm the exact Java method signatures against the API reference for the Playwright version in your project.

Need Option or approach What it changes
Capture a rectangle setClip(new Page.Clip(...)) Limits the capture to a rectangle defined by clip coordinates and dimensions.
Choose PNG or JPEG setType(...) Selects the image type. Quality applies to JPEG, not PNG.
Control output resolution setScale(...) Controls CSS-pixel versus device-pixel sizing.
Use a transparent background setOmitBackground(true) Omits the default white background; this option does not apply to JPEG.
Cover dynamic or private content setMask(List<Locator>), optionally with setMaskColor(...) Overlays selected regions so their changing content does not appear normally in the shot.
Reduce animation differences setAnimations(ScreenshotAnimations.DISABLED) Disables CSS animations, transitions, and Web Animations for the capture. Finite animations are fast-forwarded; infinite animations are canceled to their initial state, then resumed after the screenshot.
Hide the text insertion caret setCaret(ScreenshotCaret.HIDE) Hides the caret; the screenshot APIs document this as the default.
Set a capture deadline Screenshot timeout option Sets the maximum time allowed for the screenshot operation. Check the Java API reference for the option spelling in your version.

Use PNG when you need lossless image output, or JPEG when a lossy image is acceptable and you want to set its quality. For transparent backgrounds, choose a format that supports transparency; setOmitBackground(true) is not applicable to JPEG. The documented image types are PNG and JPEG; do not assume that a format is supported by a particular Playwright Java release unless its API reference says so.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Clip coordinates and full-page capture are different controls

A clip is a rectangle, while setFullPage(true) captures the page’s full scrollable extent. Choose the one that describes the desired result. When using a clip, supply valid coordinates and dimensions for the page; consult the Page API reference for the coordinate details.

Mask unstable or sensitive areas

Pass locators to the mask option when a region contains content that should not affect the screenshot, such as a changing timestamp or user-specific value. Set a mask color if the default overlay does not suit your test. Masking makes a covered region visually consistent; it does not verify the hidden content.

Make captures more repeatable

Screenshot differences can come from timing, animation, a moving caret, or changing page content—not only from a genuine design change. Apply the controls that match the source of variation:

  • Disable animations with setAnimations(ScreenshotAnimations.DISABLED) when motion makes captures inconsistent.
  • Mask only regions whose content is expected to vary; broad masks can hide real regressions.
  • Hide the caret if its position can vary while text inputs are focused.
  • Wait for the application state that matters before calling the screenshot method. A screenshot API call captures a page state; it does not establish that your app’s data or asynchronous rendering is correct.

For a one-off capture, these controls make the output easier to interpret. For automated visual checks, use the test-runner assertion workflow described below rather than treating a saved image as an assertion by itself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use screenshot assertions for visual regression tests

Playwright’s screenshot assertion API is intended for visual assertions in the Playwright test runner. The assertion waits until two consecutive page screenshots yield the same result, then compares the last screenshot with the expectation. This helps avoid comparing an image captured during a transient visual change.

The official documentation states that screenshot assertions work only with the Playwright test runner. Use the Java assertion equivalent exposed by Playwright’s Java test tooling, and configure the expected-image workflow and assertion options supported by your installed version. Options can include full-page mode, clipping, masking, animation handling, and diff thresholds; select settings based on what should count as a meaningful visual difference in your test.

Do not confuse the two tasks: page.screenshot(...) creates an image, while a screenshot assertion compares a capture with an expectation and can fail the test when the visual result differs. If you are not using Playwright Test, capture the bytes or file and use a comparison system of your choice.

See the Playwright test assertions documentation for the test-runner constraint and assertion behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the right capture method

Goal Use Output or scope
Save the visible page page.screenshot with setPath Image file for the page capture.
Capture the entire scrollable page page.screenshot with setFullPage(true) Full-page image.
Capture one component locator.screenshot Image of the matched element.
Hand image data to another system page.screenshot() without a path Image bytes in memory.
Fail a test on a visual difference Playwright Test screenshot assertion Comparison against an expectation in the test runner.

For a stable component snapshot, locator scope is usually more precise than capturing the whole page. For a long article or page-level layout check, full-page mode gives broader coverage but produces a larger image. Keep the output in memory when the next step is a programmatic pipeline; save to a file when a person or later process needs a persistent artifact.

Troubleshoot common screenshot problems

The screenshot file is missing

  • Confirm the code called setPath and that the path points where you expect relative to the process’s working directory.
  • Check that the parent directory exists and is writable by the Java process.
  • If you intended to receive bytes, remember that omitting setPath returns data rather than saving a file.

The capture is only the visible viewport

Set setFullPage(true) on the page screenshot options. A locator screenshot targets an element, not the whole page’s scrollable extent.

The element screenshot fails or captures the wrong target

  • Verify that the locator selects the intended element and that the page has reached the state in which it exists.
  • Prefer a stable role or test-oriented selector over a styling class that changes frequently.
  • Check whether your chosen locator matches more than one element; make the target unambiguous.

Repeated images differ even though the page seems unchanged

Disable animations, hide the caret, and mask known variable regions. Also ensure your application has finished the rendering or data updates relevant to the capture before taking it. Do not mask an area if changes to that area are part of what the test must detect.

Transparency or quality does not behave as expected

Transparency through setOmitBackground(true) does not apply to JPEG. Quality is a JPEG setting, whereas PNG is not controlled by that quality option. Check the selected image type and your installed version’s API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An option or method does not compile

Screenshot option names and availability are version-sensitive. Compare your code with the Java API reference for the Playwright dependency actually used by the project; do not assume an example for another release has the same method signature.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

The official Java screenshot documentation does not establish a general performance benchmark, so capture time and output size should be measured in your own browser, page, and CI environment rather than estimated from a universal number. Full-page images cover more content than viewport or element captures, and image format and scale affect the artifact you produce.

For repeatable automated runs, keep the target page state controlled and avoid comparing transient animation frames. Save only the artifacts you need, or use in-memory bytes when the next pipeline step can consume them directly. If visual assertions are used, run them through Playwright Test as required by the documented Java tooling.

Or skip the browser setup

If you want a website screenshot without managing a Playwright browser in your Java project, ScreenshotNeo is a website screenshot API and MCP server for developers. A GET request takes a URL and returns an image or PDF. Its capture flow accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and responses identify the page verdict and billing status in headers.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an image endpoint request, use this cURL example (replace the API key with your own). See the ScreenshotNeo documentation for the API and options.

curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -o shot.webp

ScreenshotNeo also has an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. The paid tiers are Starter at $5 for 3,000, Growth at $15 for 15,000, Pro at $39 for 60,000, Scale at $99 for 250,000, and Business at $249 for 1,000,000; yearly billing gives two months free. Every feature is available on every plan.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Frequently Asked Questions

Does `page.screenshot()` save a file by itself?

No. Pass a path with `Page.ScreenshotOptions.setPath(…)` to save a file; without a path, the method returns image bytes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can Playwright Java take a screenshot of one element?

Yes. Call `screenshot(…)` on a `Locator`, such as one returned by `page.locator(…)` or a role-based locator.

Can I use Playwright screenshot assertions without Playwright Test?

No. The documented screenshot assertion API works only with the Playwright test runner.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.