Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
browser automation

How to Use Playwright in Java: Maven Setup, Browser Installation, Tests, and Sample Code

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

Playwright for Java is installed from Maven, then used through a short lifecycle: create a Playwright instance, select Chromium, Firefox, or WebKit, launch a browser, open a page, perform actions or assertions, and close the resources. The example below uses Playwright Java 1.63.0, installs the matching browser binaries, visits a page, saves a screenshot, and shows how to turn the same code into a test.

What you need before writing Java code

  • Java 8 or newer.
  • Apache Maven.
  • A supported environment such as Windows, macOS, Debian, Ubuntu, or WSL. Operating-system support and minimum versions can change, so verify the current Playwright installation documentation when you standardize a build.
  • A network connection for Maven dependencies and browser downloads.

Playwright was created specifically to accommodate the needs of end-to-end testing, but the Java library is also useful for browser automation, page inspection, PDF generation, and screenshots.

Create a Maven project

Add the Playwright dependency to your project’s pom.xml. The official Java example currently uses version 1.63.0:

<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.63.0</version>
</dependency>

Put application classes under src/main/java. For example, a class named org.example.App belongs at src/main/java/org/example/App.java. Maven downloads the Java client and its transitive dependencies when you compile or run the project.

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

Install the Playwright browser binaries

The Maven dependency is not the same thing as the browser executables. Install the browser revisions expected by your Playwright release with the Java CLI:

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

You can install only one engine:

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

Linux machines may also need system libraries. Install dependencies for Chromium, or combine browser and dependency installation:

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

Each Playwright release expects specific browser revisions. Run the install command again after upgrading the Maven dependency, and keep the Java client and browser installation from the same release line. Browser downloads use an operating-system-specific cache; set PLAYWRIGHT_BROWSERS_PATH when your CI runners need a shared cache.

Write a minimal Java program

This complete program launches headless Chromium, navigates to Playwright’s site, prints the title, and closes both the browser and Playwright. The try-with-resources block is important: it prevents processes from being left behind if an operation fails.

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.
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 from the project directory:

mvn compile exec:java -D exec.mainClass="org.example.App"

The normal lifecycle is:

  1. Playwright.create() starts the Java API connection.
  2. playwright.chromium(), firefox(), or webkit() selects an engine.
  3. launch() starts a browser process.
  4. newPage() creates a tab.
  5. page.navigate() loads a URL.
  6. Locators, actions, assertions, screenshots, or other operations use the page.
  7. Close the browser and the Playwright instance.

Choose Chromium, Firefox, or WebKit

Use the engine that matches the question you are testing rather than assuming one browser represents all rendering behavior.

Engine Java selection Useful when
Chromium playwright.chromium() Testing Chromium-based rendering or a default cross-browser smoke path.
Firefox playwright.firefox() Checking Firefox-specific rendering and behavior.
WebKit playwright.webkit() Checking WebKit behavior, especially for coverage that complements Chromium and Firefox.

Playwright can also use branded Chrome and Microsoft Edge channels when your project specifically needs those installations. A branded channel is different from the Playwright-managed browser revision, so document that choice in CI and on developer machines.

Capture a screenshot in Java

The following example launches WebKit and writes a PNG file. Import java.nio.file.Paths to provide the output path:

package org.example;

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.webkit().launch();
      Page page = browser.newPage();
      page.navigate("https://playwright.dev/");
      page.screenshot(new Page.ScreenshotOptions()
          .setPath(Paths.get("example.png")));
      browser.close();
    }
  }
}

By default, browsers run headless, so no window appears. To watch the browser while debugging, disable headless mode and optionally slow each action:

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.
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();
}

Use headed mode locally when you need to see a navigation, locator, or timing problem. Keep CI headless unless the runner provides a display and you have a reason to consume the additional setup.

Turn the script into a test

Tests should synchronize with the page through locators and web-first assertions instead of arbitrary sleeps. A test framework such as JUnit can own the test lifecycle; the essential assertion pattern is:

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

// after creating page and navigating:
assertThat(page.locator("text=Installation")).isVisible();

A practical test sequence is:

  1. Create Playwright and launch the browser in a setup method.
  2. Create a fresh page for each test or fixture.
  3. Navigate to the application under test.
  4. Locate elements by accessible role, label, text, or a stable test identifier.
  5. Perform an action such as click or fill.
  6. Assert the resulting UI with assertThat(...).
  7. Close the page, browser, and Playwright instance in teardown.

Locators retry while the page reaches the expected state. A fixed delay can make a test unnecessarily slow or still fail when a server takes longer than the chosen number of milliseconds.

Useful browser and page options

Headless and slow motion

setHeadless(false) displays the browser. setSlowMo(50) adds a 50-millisecond delay to actions, which can make a local debugging session understandable without changing application behavior.

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

Contexts for isolated sessions

When several tests must run in one browser process, create separate browser contexts so cookies, local storage, and permissions do not leak between tests. Close each context after its test and close the browser at the end.

Navigation and waiting

Prefer a locator or assertion that represents the state your test needs. For example, wait for a heading or a result element rather than sleeping for an arbitrary interval. If an application loads data after navigation, assert the data-bearing locator.

Browser channels

Use Playwright-managed Chromium, Firefox, or WebKit for reproducible automation. Select a Chrome or Edge channel only when compatibility with that branded browser is a stated requirement.

CI setup and repeatability

Make browser installation an explicit CI step, cache the browser directory when your provider allows it, and pin the Maven version rather than allowing an unplanned upgrade. A reliable pipeline normally performs these actions:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Check out the source and select the required Java version.
  2. Resolve the pinned Maven dependency.
  3. Run the Playwright CLI install command for the engines used by the tests.
  4. On Linux, install the required system dependencies or use install --with-deps.
  5. Run tests headless.
  6. Publish screenshots, traces, or logs only when a test fails.

If a dependency upgrade changes the expected browser revision, an old cache can produce confusing launch failures. Clear or refresh that cache by rerunning the install command with the upgraded dependency.

Troubleshooting common failures

“Executable doesn’t exist” or browser launch failure

Cause: The Java library is present but its browser binary is not installed, or a stale browser cache is being used.

Fix: Run the CLI install command again, verify that the command uses the same project dependency version, and inspect PLAYWRIGHT_BROWSERS_PATH if CI uses a shared location.

Linux reports missing shared libraries

Cause: The runner lacks operating-system packages required by the selected browser.

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

Fix: Run install-deps chromium or install --with-deps chromium with the engine you actually use. Ensure the CI image permits package installation.

The test times out while the page is visible

Cause: The assertion may target text that is not rendered, a selector may be unstable, or the application is still waiting on data.

Fix: Prefer a role, label, or test identifier; inspect the DOM in headed mode; and assert the element that proves the operation completed. Do not solve an unknown state with a large fixed sleep.

Headed mode cannot start in CI

Cause: The runner has no display server.

Fix: Use the default headless mode in CI, or configure a supported virtual display only when visual debugging is necessary.

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

Tests pass locally but fail after an upgrade

Cause: The Maven client and cached browser revisions are out of sync, or the application changed timing and selectors.

Fix: Reinstall browsers for the new dependency, clear an incompatible cache, and review locator and assertion failures separately from browser-install errors.

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

Performance, reliability, and cost considerations

Launching a browser for every individual assertion adds process overhead. Reuse a browser process where appropriate, but isolate tests with separate contexts and pages. Parallelism can reduce wall-clock time, yet it also increases CPU, memory, browser-download, and application-environment pressure; choose worker counts based on the CI runner rather than a fixed universal number.

For reliability, keep the client and browser revisions aligned, use web-first assertions, avoid fragile CSS chains, and preserve failure artifacts. A screenshot or trace taken only on failure is usually more useful than writing large artifacts for every passing test.

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

Playwright itself is open-source software; this setup has no per-screenshot service charge. Your operational costs are Maven and browser downloads, CI minutes, machine resources, and any external application or test data services your tests call.

Or skip the browser setup

If your goal is a clean website image rather than browser-test control, ScreenshotNeo provides a website screenshot API and MCP server. A single GET request returns PNG, JPEG, WebP, or PDF. Its cleanup steps accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled.

Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. AI clients can use the MCP tools take_screenshot, get_page_info, and capture_pdf.

Using the API requires no Java browser installation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the complete parameter list and response behavior in the ScreenshotNeo API documentation. The same request from Python is:

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)

And Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets and custom viewports, retina scale, PDF paper and page controls, HTML/CSS-to-image, custom JavaScript and CSS, pre-capture clicks, hidden selectors, selector or network-idle waits, ad/tracker/request blocking, custom headers, cookies, user agents, Authorization, timezone and geolocation, transparent backgrounds, resizing, selectable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Common screenshot-API parameter names also work, which can simplify a migration.

The Free plan includes 1,000 screenshots per month without a card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free. Create a free ScreenshotNeo account to get started.

Frequently Asked Questions

Can Playwright Java run without Maven?

The documented distribution is through Maven. You can use another build system only if it resolves the same Playwright Java artifact and version correctly.

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

Which browser should I use for a first smoke test?

Chromium is a practical starting point, but meaningful cross-browser coverage should also exercise Firefox and WebKit when those engines matter to your users.

Why did a dependency upgrade break browser startup?

Playwright releases expect specific browser revisions. Reinstall the browsers after the upgrade and verify that CI is not restoring an incompatible cache.

Should screenshots be assertions in every test?

Use semantic locators and web-first assertions for behavior. Add screenshots as diagnostics or visual checks where an image is the requirement, rather than treating every screenshot as a behavioral assertion.

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.

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

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.