Playwright for Java: Documentation
Install Playwright for Java, automate Chromium, Firefox and WebKit, write stable tests, capture screenshots and debug failures with tracing.
Direct answer: Playwright for Java is a Maven-distributed browser automation API for Chromium, Firefox and WebKit. Add the Playwright dependency, install the browser binaries that match your Playwright version, launch a browser, create an isolated BrowserContext for each test, use semantic locators, and rely on auto-waiting and web-first assertions instead of fixed sleeps. The official documentation is the authoritative reference for the current dependency version and supported operating systems: Playwright Java installation.
1. What Playwright for Java provides
Playwright lets Java programs drive browser pages, interact with elements, inspect network activity, upload files, handle dialogs, emulate devices and capture screenshots or PDFs. The supported browser engines are:
| Engine | What it means |
|---|---|
| Chromium | The open-source Chromium build downloaded for the Playwright release. |
| Firefox | The Playwright-compatible Firefox binary. |
| WebKit | Playwright’s WebKit build for cross-browser coverage; it does not install branded Safari. |
| Chrome or Edge channels | Optional branded browsers already installed on the machine. Enterprise policies can affect control of these channels. |
Each Playwright release is paired with specific browser binaries. Install or update those binaries whenever you upgrade the Java dependency.
2. Requirements and Maven installation
The Java guide documents Java 8 or newer. Supported examples include Windows 11 or newer, Windows Server 2019 or WSL, macOS 14 (Sonoma) or newer, and Debian 12/13 or Ubuntu 22.04/24.04/26.04 on x86-64 or arm64. Check the installation page before standardizing a CI image because these requirements can change.
2.1 Add the dependency
Use the current version shown in the official guide rather than copying an old version into a new project:
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>CURRENT_VERSION_FROM_PLAYWRIGHT_DOCS</version>
</dependency>
2.2 Install browsers
After Maven resolves the dependency, use Playwright’s Java CLI to install browsers. The exact command is shown by the browser documentation; system dependencies can be installed separately or together with browser installation on Linux. Browser files occupy hundreds of megabytes in typical installations, so cache them deliberately in CI.
mvn exec:java -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="install"
# Linux machines that need Playwright-managed system packages
mvn exec:java -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="install --with-deps"
Run the install again after upgrading Playwright. A dependency upgrade without matching browser binaries can produce launch errors or inconsistent behavior.
3. First Java program
This headless example opens Chromium, navigates to a page and writes a PNG:
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
public class ScreenshotExample {
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");
page.screenshot(new Page.ScreenshotOptions()
.setPath(java.nio.file.Paths.get("example.png"))
.setFullPage(true));
browser.close();
}
}
}
Launched browsers run headless by default. Set setHeadless(false) when you need to watch a local run or use headed debugging on a machine with a display.
4. Browser, context and page lifecycle
A Browser is the expensive browser process. A BrowserContext is an isolated session with its own cookies, storage and permissions. A Page is a tab. Keep one browser process for a test worker and create a fresh context for every test.
try (Playwright pw = Playwright.create()) {
Browser browser = pw.chromium().launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("https://example.com");
// assertions and actions
context.close();
browser.close();
}
Fresh contexts prevent state leaking between tests while avoiding the overhead of launching a new browser process for every method.
5. Locators and reliable interactions
Locators are Playwright’s central abstraction for auto-waiting and retryability. Prefer the locator that describes user intent:
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Save")).click();
page.getByLabel("Email").fill("dev@example.com");
page.getByPlaceholder("Search").fill("Playwright");
page.getByText("Documentation").click();
page.getByTestId("results").waitFor();
Other supported families include alternative text, title and test ID. Avoid brittle CSS or XPath chains when a role, label or test ID expresses the contract more clearly.
5.1 Dynamic lists
Locator.all() returns the matches currently present and does not wait for a changing list to finish loading. Wait for a stable condition first, then enumerate:
Locator rows = page.getByRole(AriaRole.ROW);
page.getByTestId("results-loaded").waitFor();
for (Locator row : rows.all()) {
System.out.println(row.innerText());
}
6. Auto-waiting and assertions
Before an action, Playwright waits for the target to become actionable. Web-first assertions retry until the expected state is reached. The documented default assertion timeout is five seconds; configure it to match the behavior of your application rather than inserting arbitrary sleeps.
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit")).click();
assertThat(page.getByRole(AriaRole.ALERT)).hasText("Saved");
assertThat(page).hasURL("**/success");
Use an explicit wait only for a condition Playwright cannot observe through a locator or assertion. Fixed delays make suites slower and still fail when a page is slower than the chosen number.
7. Writing an end-to-end test
The test structure below creates a new context for each test and closes resources even when an assertion fails:
import com.microsoft.playwright.*;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class LoginTest {
public void loginShowsDashboard() {
try (Playwright pw = Playwright.create()) {
Browser browser = pw.chromium().launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("https://app.example.com/login");
page.getByLabel("Email").fill(System.getenv("TEST_EMAIL"));
page.getByLabel("Password").fill(System.getenv("TEST_PASSWORD"));
page.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Sign in")).click();
assertThat(page.getByRole(AriaRole.HEADING,
new Page.GetByRoleOptions().setName("Dashboard"))).isVisible();
context.close();
browser.close();
}
}
}
Keep credentials in environment variables or your CI secret store. Do not commit them to source control.
8. Configuration you will use often
| Need | Playwright Java approach |
|---|---|
| Headed debugging | new BrowserType.LaunchOptions().setHeadless(false) |
| Slow-motion local diagnosis | Set a launch slow-motion value while debugging, then remove it in CI. |
| Viewport | browser.newContext(new Browser.NewContextOptions().setViewportSize(1440, 900)) |
| Mobile or device emulation | Use the device descriptors exposed by the Java API and override only what your test needs. |
| Authentication reuse | Save and load storage state for a controlled test account; still use a fresh context per test. |
| Network control | Use context or page routing to inspect, fulfill or abort requests. |
| Downloads and uploads | Use the download and file chooser event APIs instead of guessing filesystem timing. |
Read the Java API reference for the exact overloads available in your installed release.
9. Screenshots and PDFs with Playwright
Capture a viewport, a full page or a single element. Full-page capture is useful for documentation but can produce very tall files when a page contains long feeds.
page.screenshot(new Page.ScreenshotOptions()
.setPath(java.nio.file.Paths.get("full-page.webp"))
.setFullPage(true)
.setType(ScreenshotType.WEBP));
page.locator("main article").screenshot(new Locator.ScreenshotOptions()
.setPath(java.nio.file.Paths.get("article.png")));
page.pdf(new Page.PdfOptions()
.setPath(java.nio.file.Paths.get("page.pdf"))
.setFormat("A4")
.setPrintBackground(true));
For deterministic images, wait for the relevant content and fonts, disable animations in test CSS, and use a fixed viewport and timezone. If the page lazy-loads images, scroll or wait for the content before taking a full-page shot.
10. Debugging with tracing
Tracing records browser operations and network activity, which helps explain navigation, locator and resource failures. The Java context tracing API does not record test assertion calls such as expect; keep the assertion failure and trace together.
BrowserContext context = browser.newContext();
context.tracing().start(new Tracing.StartOptions()
.setScreenshots(true)
.setSnapshots(true)
.setSources(true));
Page page = context.newPage();
page.navigate("https://example.com");
// test actions
context.tracing().stop(new Tracing.StopOptions()
.setPath(java.nio.file.Paths.get("trace.zip")));
context.close();
Open the resulting archive with Playwright’s trace viewer as described in the Tracing API reference. Enable tracing for failure diagnostics or configure it in the test runner when you need consistent artifacts.
11. Or skip the browser setup
If your goal is a clean website image rather than browser automation itself, ScreenshotNeo provides a single screenshot API request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed; the response identifies the result with X-Page-Verdict and X-Billed headers. An MCP server exposes take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients.
See the ScreenshotNeo API documentation for all options. The same endpoint works from Java through any HTTP client:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const fs = require('node:fs');
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
fs.writeFileSync('shot.webp', Buffer.from(await res.arrayBuffer()));
Plans include 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000. Every feature is on every plan. Create a free ScreenshotNeo account.
12. Reliability, performance and cost notes
- Reuse a browser process, but isolate tests with fresh contexts.
- Cache Maven dependencies and Playwright browser binaries in CI, while invalidating the cache when the Playwright version changes.
- Prefer semantic locators and web-first assertions to reduce retries caused by brittle selectors.
- Keep trace capture focused on failures or diagnostic runs because screenshots, snapshots and network data increase artifact size.
- Use fixed viewport, timezone, locale and test data when comparing screenshots.
- Parallelize at the context or worker level only when the application and test accounts can safely handle concurrent traffic.
- Playwright itself has no per-action service charge; your costs are the machines, CI minutes, browser storage and any external services you automate.
13. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Browser executable missing | Matching binaries were not installed or the Playwright version changed. | Run the Java CLI browser install again and update the CI cache key. |
| Linux launch failure mentioning shared libraries | System dependencies are absent. | Install dependencies with the documented --with-deps flow or provision them in the image. |
| Click times out | The locator is ambiguous, hidden, covered, or the page has not reached the expected state. | Use a role or label locator, assert visibility/state, and inspect a trace. Avoid force-clicking unless the UI contract truly requires it. |
| Assertion times out after five seconds | The eventual state is slower, incorrect, or the selector does not match. | Check the locator and application logs; increase the assertion timeout only for a known slower operation. |
| Tests pass alone but fail in a suite | Cookies, storage or server data leak between tests. | Create a new BrowserContext and use independent test data for every test. |
| Dynamic list is incomplete | Locator.all() reads the current matches immediately. |
Wait for a loading marker or expected count before enumerating. |
| Trace does not explain an assertion | Context tracing omits test assertion calls. | Keep assertion logs and failure output with the trace; use tracing to inspect browser and network behavior. |
| Branded Chrome or Edge behaves differently | Channel policies or enterprise configuration affect the installed browser. | Reproduce with the default Playwright browser, then review channel and policy configuration. |
14. Short FAQ
Does Playwright Java install Safari?
No. It supports the WebKit engine. Safari itself is not installed or controlled as a branded browser.
Do I need a new browser process for every test?
No. Reuse the browser process and create a new in-memory BrowserContext for each test.
Can I use Playwright Java without Maven?
The official Java distribution is documented as Maven modules. Other build systems can consume the same artifacts, but follow the dependency and browser-install steps for the chosen build tool.
Why are fixed sleeps discouraged?
They wait longer than necessary on fast runs and still fail when the application takes longer. Locators and web-first assertions wait for observable conditions.
What does a trace contain?
Context tracing contains browser operations and network activity, plus optional screenshots, snapshots and sources. It does not contain test assertion calls.
Where should I check release-sensitive details?
Use the current Playwright Java installation guide, browser guide and API reference for the dependency version, operating-system support and exact method signatures.


