To use Playwright with Java, add the com.microsoft.playwright Maven dependency, install the matching browser binaries, then launch a browser and interact with pages through Playwright’s Java API. This tutorial walks through setup, Chromium/Firefox/WebKit, reliable locators and assertions, test isolation, code generation, and common fixes. The official Java guide currently lists Playwright version 1.63.0 and Java 8 or higher; verify the current version on the official installation page before starting.
What you need before installing Playwright Java
- A Java development kit. Playwright Java requires Java 8 or higher according to the official Java installation guide. Use the Java version your project and CI environment support.
- Maven for dependency management and running the examples. The commands below assume a Maven project and a main class at
org.example.App. - Browser binaries that match the Playwright release. The Java package does not make arbitrary locally installed browser versions interchangeable with Playwright’s supported revisions.
The same Java API supports Chromium, Firefox, and WebKit. Browser coverage is useful when checking differences between engines; for an everyday smoke test, start with Chromium and add the others where your application’s support requirements call for them.
Add Playwright to a Maven project
Add the Playwright dependency to your pom.xml. The official guide currently shows version 1.63.0 (retrieved September 29, 2026); check its page for the current version when creating or updating a project.
<dependencies>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.63.0</version>
</dependency>
</dependencies>
Compile and run a main class with Maven’s Exec plugin, as shown in the Java guide:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
mvn compile exec:java -D exec.mainClass="org.example.App"
If your project already uses a build plugin or test framework, keep its existing conventions and add the dependency there. The key is that the Playwright library version and installed browser binaries remain aligned.
Install the browsers Playwright will launch
After adding the dependency, use Playwright’s CLI to download its default browser binaries:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install"
To install a particular engine, supply its name, for example chromium, firefox, or webkit:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install webkit"
On Linux or in a CI image missing system libraries, install required operating-system dependencies as well. For Chromium, the documented command combines browser installation and system dependencies:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps chromium"
You can also use install-deps when system dependencies are the missing piece. Browser revisions change with Playwright releases, so after upgrading the Maven dependency, rerun the install command in developer and CI environments. This avoids failures caused by a library expecting a different browser revision than the one available locally.
Launch a browser and capture a page
This minimal Java program launches Chromium in headless mode, opens a page, navigates to a URL, and saves a screenshot as example.png. Place it in src/main/java/org/example/App.java to match the Maven command above.
package org.example;
import com.microsoft.playwright.*;
import java.nio.file.Paths;
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/");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("example.png")));
browser.close();
}
}
}
The try-with-resources block closes the Playwright instance. Closing the browser explicitly makes the lifecycle clear; it is also closed when Playwright is shut down. By default, browser launches are headless. To watch the browser during debugging, change the launch line to:
Rank #2
Browser browser = playwright.chromium().launch(
new BrowserType.LaunchOptions().setHeadless(false));
You can slow actions for inspection with setSlowMo on LaunchOptions. Use headed mode and slow motion for diagnosis, not as a substitute for synchronizing a test with the page’s actual state.
Choose Chromium, Firefox, or WebKit
Select an engine from the Playwright instance and use the same browser workflow:
Browser chromium = playwright.chromium().launch();
Browser firefox = playwright.firefox().launch();
Browser webkit = playwright.webkit().launch();
Run the browser install command for the engine or engines your project uses. Cross-browser testing can reveal engine-specific behavior, but costs additional download space and execution time. A practical approach is to run fast, high-value checks in your primary engine and include other engines in the CI coverage that matches your product’s supported browsers.
Build reliable tests with isolated contexts
A BrowserContext is an in-memory, isolated browser profile. It separates cookies, storage, and other profile state. For tests, launch a browser once where appropriate, then create a fresh context for each test instead of sharing user state:
Browser browser = playwright.chromium().launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();
// Run one test using this page and context.
context.close();
browser.close();
In a test framework, put browser setup and teardown in the appropriate fixture or lifecycle methods. Create and close a context per test, including when a test fails; this prevents cookies or local storage from leaking into the next test. The official browser-context guidance recommends this per-test isolation.
Free tools Windows power users keep installed
One-click scans. No signup required.
Use locators that reflect how people use the page
Playwright’s recommended locator methods include getByRole, getByText, getByLabel, getByPlaceholder, getByAltText, getByTitle, and getByTestId. Prefer role locators for interactive controls, such as buttons and links, and label locators for form fields. Use text locators for non-interactive content. These approaches describe the user-facing interface or an explicit test contract, rather than depending on fragile CSS structure or XPath tied to implementation details.
For example, a sign-in flow can fill labeled inputs, click the named button, and assert the resulting message:
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import com.microsoft.playwright.options.AriaRole;
page.getByLabel("User Name").fill("John");
page.getByLabel("Password").fill("secret-password");
page.getByRole(AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Sign in")).click();
assertThat(page.getByText("Welcome, John!")).isVisible();
Locators resolve against the current DOM when each action runs, which is helpful when a client-side framework re-renders the page. If a locator matches more than one element, make the intended name, role, or test ID specific rather than relying on whichever element happens to appear first. See the Java locators guide for supported locator strategies.
Replace arbitrary sleeps with auto-waiting and assertions
Playwright actions wait for their target to become actionable, and Playwright assertions retry until the expected condition is met or the assertion times out. Use those mechanisms to synchronize on what the test needs, rather than guessing how long a page will take.
Recommended Free Tools
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
assertThat(page).hasTitle("Account");
assertThat(page.getByRole(AriaRole.HEADING,
new Page.GetByRoleOptions().setName("Your account"))).isVisible();
For example, after clicking a navigation control, assert that the destination heading is visible or that the page has the expected title. A fixed sleep may be too short on a slow run and unnecessarily long on a fast one. It also does not establish that the condition your test cares about has become true.
Be cautious with Locator.all(): it returns immediately and does not wait for a set of matches to appear. If a list is still loading or changing, first wait for a meaningful state—such as a result count or a known item—then read the list. Otherwise, the returned collection may reflect an incomplete or changing DOM. The Locator API documentation describes this behavior.
Record a starter workflow with Codegen
Playwright Codegen opens a browser for interaction and Playwright Inspector for recording and reviewing generated tests. Run it from the project directory:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI
-D exec.args="codegen demo.playwright.dev/todomvc"
- Interact with the page in the opened browser: click controls and fill fields as a user would.
- In Inspector, add useful assertions about visibility, text, or values rather than recording actions alone.
- Copy the generated Java code and run it in your project.
- Edit generated names and assertions, and extract repeated flows into page objects or helper methods if that improves maintainability.
Codegen prioritizes role, text, and test-ID locators and attempts to make ambiguous matches unique. Treat its output as editable starter code: a recorded click is not automatically a meaningful test, and an assertion should verify the behavior your application is supposed to provide. See the Java Codegen guide.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Practical trade-offs: coverage, setup, and runtime
- Browser coverage: Chromium, Firefox, and WebKit use the same Java API, but each engine requires its own browser binary. Add engines when they answer a real compatibility question.
- Debugging: Headed mode and slow motion make interactions visible. Headless mode is the default and is generally suited to unattended runs.
- Locator resilience: Role, label, and test-ID locators are usually clearer contracts than selectors based on deeply nested markup. Choose the method that expresses the element’s intended identity.
- State control: Per-test contexts add setup and cleanup work, but isolate cookies and storage so a previous test is less likely to change the next test’s result.
- Environment cost: Browser downloads and Linux system dependencies take disk space and CI setup time. Cache or provision them according to your CI platform, and reinstall supported browser revisions when the Playwright version changes.
Troubleshooting common Playwright Java failures
Browser executable is missing or its revision does not match
Cause: The Maven dependency is installed, but the corresponding browser binaries were not downloaded, or the Playwright version changed after the previous installation.
Rank #4
Fix: Run the CLI install command again from the project using the same dependency version. Specify the needed engine, such as install chromium, if you do not use the defaults.
Browser starts locally but fails in Linux CI
Cause: The runner may lack operating-system libraries required by the browser, even though the Playwright binary is present.
Fix: On supported Linux environments, run install --with-deps chromium or use install-deps as appropriate, then rerun the job. Check that the CI image permits installation of those dependencies.
An element is not found or a click fails intermittently
Cause: The locator may be too dependent on markup, ambiguous, or evaluated before the expected UI state exists.
Fix: Prefer a role or label locator with a specific accessible name, then use a web-first assertion to wait for the required state. If multiple elements match, narrow the locator to the intended control.
A list assertion sometimes sees too few elements
Cause: Locator.all() does not wait for the list to finish loading.
Fix: Wait for a meaningful readiness condition or expected item/count before retrieving all matches.
Best Value
One test passes alone but fails after another test
Cause: Tests may share browser profile state such as cookies or local storage.
Fix: Give each test a fresh BrowserContext, and close it during teardown even when a test fails.
Or skip the browser setup
For a one-off website screenshot, a browser automation project can be more setup than you need. ScreenshotNeo is a website screenshot API and MCP server from Yorker Media: a single GET request returns an image or PDF. This cURL example saves a WebP screenshot of the target URL; see the ScreenshotNeo API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Before capture, ScreenshotNeo can accept cookie/consent banners as a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Sign up free for 1,000 screenshots a month, with no card required.
Frequently Asked Questions
Can I run Playwright Java without Maven?
This tutorial uses Maven because that is the installation route covered by the official Java guide. The examples depend on having the Playwright Java library and matching browser binaries available to the project.
Does Codegen produce finished tests?
No. It records a useful starting workflow and generates locators, but you should edit the code and add assertions that verify the behavior you intend to test.
Quick Recap
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.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute

