How to Use Playwright in Java with Sample Code
Install Playwright with Maven, launch Chromium, Firefox or WebKit, navigate, test pages and capture screenshots with runnable Java examples.
Use Playwright in Java by adding the Maven dependency, installing the browser binaries, then creating a Playwright instance, launching a browser, opening a page, and closing resources. The same lifecycle works with Chromium, Firefox, and WebKit:
Playwright.create() -> chromium(), firefox(), or webkit() -> launch() -> newPage() -> navigate() -> close()
This guide gives you a complete Maven project, navigation and screenshot programs, headed debugging, browser installation commands, test code, configuration options, CI guidance, troubleshooting, and a hosted alternative when you do not want to manage browser binaries.
1. Create a Maven project
Playwright Java is distributed through Maven. Add the dependency below to pom.xml. The example uses Playwright 1.63.0; keep the client and browser revisions aligned when upgrading.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>playwright-java-example</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.63.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.5.0</version>
</plugin>
</plugins>
</build>
</project>
Playwright supports Java 8 or newer and common Windows, macOS, Debian, Ubuntu, and WSL environments. Check the current Playwright installation documentation when your target operating system or Java runtime is release-sensitive.
2. Install browser binaries
The Maven dependency supplies the Java API. Install the browser revisions required by that Playwright release with the CLI:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install"
You can install one engine or include Linux system dependencies:
# Install only WebKit
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install webkit"
# Install Chromium's Linux dependencies
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install-deps chromium"
# Install Chromium and its Linux dependencies
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps chromium"
Run the install command again after upgrading the Maven dependency. Each Playwright release expects specific browser revisions. In CI, install browsers in the image or setup step using the same dependency version that the test run uses. Set PLAYWRIGHT_BROWSERS_PATH when several jobs should share a browser cache.
3. Minimal navigation program
Create src/main/java/org/example/App.java:
package org.example;
import com.microsoft.playwright.*;
public class App {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("https://playwright.dev");
System.out.println(page.title());
browser.close();
}
}
}
Run it with:
mvn compile exec:java -D exec.mainClass="org.example.App"
Playwright and the browser are closed deterministically by the try-with-resources block and the explicit browser.close(). For longer programs, also close contexts and pages you create.
4. Choose Chromium, Firefox, or WebKit
Use the engine whose rendering behavior you need:
try (Playwright playwright = Playwright.create()) {
Browser chromium = playwright.chromium().launch();
Browser firefox = playwright.firefox().launch();
Browser webkit = playwright.webkit().launch();
// Use each browser, then close it.
chromium.close();
firefox.close();
webkit.close();
}
| Engine | Use it when | Operational consideration |
|---|---|---|
| Chromium | You need Chromium rendering or a Chromium-based CI baseline. | Install the Chromium revision and Linux dependencies when required. |
| Firefox | You want Firefox rendering coverage. | Install the Firefox revision for your Playwright release. |
| WebKit | You need WebKit coverage similar to Safari behavior. | WebKit binaries can add a separate download and dependency step. |
Playwright also supports branded Chrome and Microsoft Edge channels when your project must exercise those installed browsers. Use a channel only when that browser is part of your compatibility requirement.
5. Capture a screenshot
The following program launches WebKit headlessly, navigates to a page, and writes a PNG:
package org.example;
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class Screenshot {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.webkit().launch();
Page page = browser.newPage();
page.navigate("https://playwright.dev/");
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("example.png")));
browser.close();
}
}
}
Launches are headless by default. For a visible browser and slower actions while debugging:
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.firefox().launch(
new BrowserType.LaunchOptions()
.setHeadless(false)
.setSlowMo(50));
Page page = browser.newPage();
page.navigate("https://playwright.dev/");
browser.close();
}
setSlowMo adds a delay between actions so you can observe the sequence. Remove it for normal runs.
6. Useful page and context configuration
Viewport and device-like settings
BrowserContext context = browser.newContext(
new Browser.NewContextOptions()
.setViewportSize(1440, 900)
.setDeviceScaleFactor(2));
Page page = context.newPage();
Create a context per isolated test or scenario. Contexts keep cookies and storage separate without requiring a new browser process.
Navigation and waiting
page.navigate("https://example.com",
new Page.NavigateOptions().setWaitUntil(WaitUntilState.NETWORKIDLE));
Prefer locator auto-waiting and explicit readiness conditions over arbitrary sleeps. Pages with long polling may never become network-idle; wait for the selector that proves the content you need is ready.
Locators, clicks, and selectors
page.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Sign in")).click();
page.locator("input[name='email']").fill("dev@example.com");
page.locator("#results").waitFor();
Stable roles, labels, and test identifiers are less fragile than deeply nested CSS selectors. Use CSS selectors when you need a specific element for capture or interaction.
Screenshot options
page.screenshot(new Page.ScreenshotOptions()
.setPath(Paths.get("full-page.webp"))
.setFullPage(true)
.setType("webp"));
Common options include a file path, PNG/JPEG/WebP type, full-page capture, and quality for JPEG or WebP. Full-page shots can be expensive for very tall pages; capture a specific element when that is all you need.
7. Turn the script into a test
Use locators and web-first assertions so the assertion waits for the page state instead of relying on a fixed delay. The Java assertion example below checks that the Installation text is visible:
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import com.microsoft.playwright.*;
public class DocsTest {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("https://playwright.dev/");
assertThat(page.locator("text=Installation")).isVisible();
browser.close();
}
}
}
For a real test suite, create shared setup and teardown, keep each test’s browser context isolated, and add tracing or headed mode when diagnosing a failure. Playwright’s Java workflow also includes Codegen, single and multiple tests, and tracing.
8. Or skip the browser setup
If your goal is a reliable image or PDF rather than browser automation, ScreenshotNeo provides a hosted screenshot API. It accepts one GET request and returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation for the complete parameter reference.
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 q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing result. An MCP server provides 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 without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
9. Browser installation and CI troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Executable doesn’t exist | The browser revision was not installed or the dependency version changed. | Run the CLI install command again using the current Maven version. |
| Linux launch fails with missing shared libraries | System browser dependencies are absent. | Run install-deps chromium or install --with-deps chromium in the CI image. |
| Browser opens locally but not in CI | CI has no display server or required dependencies. | Keep headless mode enabled and install the engine’s Linux dependencies. |
| Tests hang while waiting for network idle | The page uses analytics, polling, or another long-lived request. | Wait for a meaningful locator or application-ready selector instead. |
| Element is not found | The selector is unstable, the frame is wrong, or the element has not rendered. | Use a role, label, or test id; wait for the locator; inspect frames and page state. |
| Screenshot is clipped | The capture targets the viewport or an element with constrained dimensions. | Use setFullPage(true) for the document or capture the intended element after it has rendered. |
| Different results after an upgrade | Playwright changed its bundled browser revision or rendering behavior. | Pin the Maven version, reinstall browsers, and review the release notes before updating CI. |
10. Performance, reliability, and cost considerations
- Reuse a browser process: launch one browser per worker and create separate contexts for tests. Browser startup is heavier than creating a context or page.
- Limit full-page captures: very tall pages require more layout, memory, and image encoding work. Capture a component when a component screenshot meets the requirement.
- Control concurrency: too many simultaneous pages can exhaust CPU, memory, file descriptors, or CI time. Start with a small worker count and increase it while observing resource limits.
- Make readiness explicit: wait for a stable selector, required response, or application state. Fixed sleeps make runs slower and still fail on slower environments.
- Keep versions together: commit the Maven version and run browser installation from the same build definition so local and CI revisions match.
- Cache browser binaries in CI: a shared
PLAYWRIGHT_BROWSERS_PATHcan avoid repeated downloads, provided the cache key includes the Playwright version and operating system. - Budget hosted capture separately: with ScreenshotNeo, only clean shots are billed; failed loads, bot checks, blank pages, timeouts, and cache hits are free. Its plans range from 1,000 free monthly shots to paid tiers of 3,000, 15,000, 60,000, 250,000, and 1,000,000 shots.
11. Java Playwright checklist
- Add
com.microsoft.playwright:playwrightto Maven. - Run the Playwright CLI browser installation command.
- Create one
Playwrightinstance for the run. - Choose Chromium, Firefox, or WebKit and launch it.
- Create a context and page with the viewport and device settings you need.
- Navigate and wait for a meaningful page state.
- Use locators for interactions and web-first assertions for tests.
- Capture a screenshot or PDF, then close pages, contexts, browsers, and Playwright.
- Pin versions and repeat browser installation after dependency upgrades.
12. FAQ
Does Playwright Java require Selenium?
No. Playwright Java is its own browser automation library and manages its supported browser engines through its Maven package and CLI.
Can I run Playwright without showing a browser window?
Yes. Headless mode is the default. Set setHeadless(false) only when you need to observe the browser.
Should I launch a browser for every test?
Usually no. Reuse a browser process and create isolated contexts for tests or scenarios.
Why must I reinstall browsers after changing the dependency?
Playwright releases are tied to particular browser revisions. Reinstalling keeps the executable revision compatible with the Java client.
When is a screenshot API preferable to Playwright?
Use a hosted API when you need captures without maintaining browser binaries, CI dependencies, consent cleanup, or automation code. Use Playwright when you need arbitrary browser interactions and assertions inside your own process.


