ScreenshotNeo

BlogHow-to

How to Capture Website Screenshots with Playwright in Java

Capture viewport, full-page, or element screenshots with Playwright Java. Set up browsers, choose image options, and troubleshoot common capture issues.

By the ScreenshotNeo team4 October 20268 min read

Use Playwright Java’s Page.screenshot method and pass a path through Page.ScreenshotOptions.setPath. Use setFullPage(true) for the full scrollable page, or take a locator screenshot for a single element. The examples below save PNG files; you can also return screenshot bytes for further processing. Playwright browsers run headless by default. See the official Playwright Java screenshot guide.

1. Set up Playwright Java

Playwright Java requires Java 8 or higher according to its introductory documentation. Add the Playwright Java dependency to your Maven project, then install the browser binaries. The exact dependency version should match the version you intend to use; Playwright’s browser binaries are version-specific.

mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install"

To install just one browser, name it in the CLI arguments, for example install webkit. If you update Playwright, rerun the install command so the matching browser binaries are available. Check the official Java installation guide and browser installation guide for the current setup details.

2. Capture a viewport screenshot

This complete Java program launches Chromium, opens a page, navigates to a URL, and saves the visible viewport to screenshot.png. Replace the URL and output path as needed. Chromium is one of the available browser choices; Playwright’s official introductory screenshot example uses WebKit.

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

public class ScreenshotExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch();
      Page page = browser.newPage();
      page.navigate("https://example.com");
      page.screenshot(new Page.ScreenshotOptions()
          .setPath(Paths.get("screenshot.png")));
      browser.close();
    }
  }
}

Run the class using your project’s usual Java or Maven entry point. The screenshot path is relative to the process working directory if you supply a relative path. For repeatable automation, use an explicit output directory and ensure it exists before capture.

3. Choose viewport, full-page, or element capture

Capture Use it for Java API
Viewport The currently visible browser area page.screenshot(...)
Full page A single image of the whole scrollable page setFullPage(true)
Element A particular component or region page.locator(selector).screenshot(...)
Clip A rectangular part of the page setClip(...)

Full-page screenshot

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

A full-page capture behaves like a very tall screen that displays the scrollable page. It may produce a large image on long pages, so use viewport or element capture when you only need a section.

Element screenshot

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

A locator screenshot scrolls the element into view and waits for actionability checks before capturing its bounds. If the selector matches nothing, the capture cannot proceed. A covered element may not be visible in the resulting image. For a scrollable element, the screenshot includes its currently scrolled content rather than automatically expanding its inner scroll area. See the Locator API.

Clip a page rectangle

Use a clip when you need a fixed region in the page coordinate space. The clip rectangle has an origin and dimensions; confirm it overlaps the rendered page and does not have zero or negative dimensions.

page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("region.png"))
    .setClip(100, 120, 640, 360));

4. Write to a file or keep the image bytes

Set a path to write directly to disk. Omit the path to get the screenshot as a byte[], which is useful for an image-processing step, an upload, or a pixel-diff workflow.

byte[] png = page.screenshot();
java.nio.file.Files.write(Paths.get("screenshot.png"), png);

Use a path when the desired result is a file. Use bytes when another part of the program consumes the image; this avoids choosing a temporary filename, though the image still occupies memory while represented as a byte array.

5. Configure image format and output size

Playwright Java supports PNG, JPEG, and WebP screenshot output. PNG is the default. JPEG and WebP have quality settings; those quality settings do not apply to PNG. WebP screenshot support was added in Playwright 1.62, so verify the library version before relying on it. See the Page screenshot options and release notes.

// JPEG output and lossy quality setting
page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("screenshot.jpg"))
    .setType(ScreenshotType.JPEG)
    .setQuality(80));

For WebP, select the WebP type in a Playwright version that supports it. A WebP quality of 100 is lossless; lower values are lossy. Match the file extension to the selected format so downstream tools interpret the file as expected.

Pixel scale is separate from image format. The default device scale produces pixels per device pixel. Choose CSS scale to produce one output pixel per CSS pixel, which can keep high-DPI screenshots smaller. Select the scale according to whether output dimensions should follow device pixels or CSS layout pixels.

6. Make screenshots more repeatable

  • Disable animations: use the screenshot animation option when motion would make captures differ between runs.
  • Hide the caret: prevent a blinking text cursor from changing the image.
  • Apply a stylesheet: add screenshot-specific CSS to control the capture presentation.
  • Mask changing regions: mask matching locators such as timestamps or randomized content; the documented default mask color is pink (#FF00FF), and the mask color can be chosen explicitly.
  • Set an appropriate timeout: the screenshot API default is 30,000 milliseconds. Override it for the call or configure page/context defaults when the capture has a different time budget.

Example of masking a dynamic region:

page.screenshot(new Page.ScreenshotOptions()
    .setPath(Paths.get("stable.png"))
    .setMask(java.util.List.of(page.locator(".last-updated"))));

Option names and availability can vary by Playwright release. Consult the Java Page API for the exact methods available to your dependency version.

7. Wait for the page state you need

A screenshot captures the rendered state at the time it runs. A navigation completing does not guarantee that every client-rendered widget, image, or delayed update has reached the state you want. Wait for a meaningful selector when possible, or wait for a deliberate state transition in the page before calling screenshot. Avoid relying on an arbitrary delay unless the page offers no reliable readiness signal.

For full-page captures of pages that load images as you scroll, verify that the desired content has loaded before saving. Playwright’s full-page option captures the scrollable page as a tall screen; it does not mean every site-specific lazy-loading behavior has necessarily completed.

8. Common errors and fixes

Symptom Likely cause Fix
Browser executable is missing The browser binary for this Playwright release was not installed, or the library was upgraded. Run the Playwright CLI install command again for the selected browser.
Screenshot call times out The page or locator did not reach the needed state before the timeout. Wait for the expected page state, confirm the selector exists, and adjust the screenshot timeout only if the longer wait is justified.
Output file is not where expected A relative path is resolved from the process working directory. Use an absolute path or log the working directory and create the destination directory first.
Element screenshot fails The selector matched no visible element or the element was not ready. Check the selector, wait for the element, and confirm it is visible and attached.
Image format is unexpected The file extension and selected screenshot type do not match, or the installed version lacks a format feature. Align the extension and type, and check the Playwright release notes for version support.
Image differs across runs Animations, caret blink, dynamic content, or device scale changed the output. Disable animations, hide the caret, mask dynamic areas, and hold browser and viewport settings constant.
Full-page image is huge The document is very long or device scale yields many pixels. Capture a smaller region or element, use CSS pixel scale, or split the workflow into focused screenshots.

9. Performance, reliability, and cost

Playwright performs the capture in a real browser process, so setup includes the Java library and compatible browser binaries. For repeated jobs, avoid launching a new browser for every image when a managed browser lifecycle fits your application; reuse a browser and create pages or contexts for isolated work, then close resources reliably. Keep full-page captures limited to pages and image sizes you actually need because very tall outputs use more time and memory than a viewport image.

For reliability, pin the Playwright dependency version in your build and install the matching browser binaries in each environment. Fix the viewport, device scale, browser choice, page state, and masking rules when comparing screenshots. A successful image write says that a file was produced; it does not by itself prove the page showed the intended content, so validate the relevant page state in your workflow.

With Playwright, costs are your own compute, browser execution, storage, and any network or infrastructure used to run the job; the research sources do not provide a universal benchmark or fixed cost. Estimate using your page count, capture dimensions, concurrency, and retention needs on your own workload.

10. Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. Instead of installing Playwright and browser binaries, send one GET request with the target URL. See the ScreenshotNeo API documentation for parameters and configuration.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));

Cookie banners, popups, and chat widgets are removed before capture. Bot checks, blank pages, failed loads, and cache hits are never billed; response headers identify the page verdict and billing status. An MCP server lets AI agents use the take_screenshot, get_page_info, and capture_pdf tools. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up free for 1,000 screenshots a month, with no card required.

11. FAQ

Can Playwright save a screenshot without writing a file?

Yes. Call page.screenshot() without a path; it returns the image as a Java byte[].

Does a full-page screenshot include the whole document?

setFullPage(true) captures the scrollable page as a tall image. Lazy-loaded or delayed content may still need page-specific waits.

Can I capture just one component?

Yes. Call screenshot on a locator. The element is scrolled into view and its bounds are captured.

Which image format should I use?

PNG is the default. Choose JPEG or WebP when their size and quality characteristics suit the consumer of the image; check your Playwright version for WebP support.

Sources