Sample Playwright Projects Using Java
Build Playwright Java projects with Maven or Gradle, install browsers, write reliable tests, run CI, and automate clean screenshots.
Short answer: a useful Playwright Java project has four pieces: a Maven or Gradle build, the Playwright Java dependency, browser binaries installed for that dependency version, and tests that use locators plus assertions. Start with the one-file Maven example below, then move to JUnit, Gradle, and CI when the project grows.
1. Minimal Maven project that opens a page
Create pom.xml and src/main/java/org/example/App.java. The dependency version shown in the research material was 1.63.0; check the live Java introduction before pinning a new project.
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId><artifactId>sample-playwright-java</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>
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(new BrowserType.LaunchOptions().setHeadless(true));
Page page = browser.newPage();
page.navigate("https://playwright.dev/");
System.out.println(page.title());
browser.close();
}
}
}
Install the browser binary matching the library, then run mvn compile exec:java -Dexec.mainClass="org.example.App".
2. Browser choice and launch options
Playwright supports Chromium, Firefox, and WebKit through one Java API. Managed Chromium is not the same binary as branded Chrome or Edge.
Browser browser = playwright.firefox().launch();
// playwright.webkit().launch();
// playwright.chromium().launch();
Browser debug = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(150));
Reuse a browser process but create an isolated context per test:
try (Playwright pw = Playwright.create(); Browser browser = pw.chromium().launch()) {
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("https://example.com");
context.close();
}
3. JUnit test with reliable locators
The official test-runner guide documents Maven and Gradle integrations. Add JUnit 5 to Maven (use versions approved by your project):
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.12.2</version><scope>test</scope></dependency>
import com.microsoft.playwright.*;
import org.junit.jupiter.api.*;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
class HomePageTest {
static Playwright pw; static Browser browser; BrowserContext context; Page page;
@BeforeAll static void start(){ pw=Playwright.create(); browser=pw.chromium().launch(); }
@BeforeEach void open(){ context=browser.newContext(); page=context.newPage(); }
@AfterEach void close(){ context.close(); }
@AfterAll static void stop(){ browser.close(); pw.close(); }
@Test void headingIsVisible(){
page.navigate("https://playwright.dev/");
assertThat(page.locator("h1")).containsText("Playwright enables reliable end-to-end testing");
}
}
Run with mvn test. Locators wait for actionable elements and web-first assertions retry until they pass or time out. Prefer role, label, and stable test-id locators over brittle XPath and fixed sleeps.
4. Equivalent Gradle project
Use Gradle when the repository already uses it:
plugins { id 'java' }
repositories { mavenCentral() }
dependencies {
implementation 'com.microsoft.playwright:playwright:1.63.0'
testImplementation 'org.junit.jupiter:junit-jupiter:5.12.2'
}
test { useJUnitPlatform() }
Place tests under src/test/java, install the matching browser, and run ./gradlew test. Keep dependency resolution and commands within one build tool.
5. Browser installation and CI
- Resolve the Java dependency.
- Run the Playwright CLI install command for that exact version.
- On Linux CI, install browser operating-system dependencies using the documented option or your image’s package manager.
- Run the same test command used locally.
The browser guide explains version-linked binaries. Cache them in CI with a key containing the Playwright version and refresh after upgrades. Java alone is insufficient if the worker lacks browser executables or shared libraries. The CI guide has provider examples.
6. Debugging and artifacts
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(300));
page.screenshot(new Page.ScreenshotOptions().setPath(java.nio.file.Paths.get("failure.png")));
java.nio.file.Files.writeString(java.nio.file.Paths.get("failure.html"), page.content());
Use tracing around a context for CI diagnosis and retain the trace artifact. Close pages, contexts, browsers, and Playwright in fixtures.
7. Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
| Executable doesn’t exist | Browser not installed for this version. | Run the matching Playwright install command. |
| Missing shared library | Linux image lacks browser dependencies. | Install documented OS dependencies. |
| Locator timeout | Wrong locator, failed navigation, or frame. | Check URL/response, use a role or label, and target the correct frame. |
| Flaky assertion | Fixed sleeps or unstable selectors. | Use auto-waiting locators and retrying assertions. |
| Shared login state | Contexts reused between tests. | Create a fresh context or deliberately use saved storage state. |
| Only CI fails | Different browser, fonts, permissions, viewport, or network. | Install dependencies, pin versions, and retain artifacts. |
8. Performance, reliability, and cost
- Reuse a browser process; isolate tests with contexts.
- Parallelize only when the application and test data are concurrency-safe.
- Avoid fixed delays and unnecessary navigation.
- Key browser caches by Playwright version.
- Close resources in fixtures to prevent leaked workers.
- Your direct cost is the machine or CI minutes running Java and browsers; tracing, video, and parallel workers consume more resources.
9. Or skip the browser setup
If you need a clean image or PDF instead of an interactive test, ScreenshotNeo provides a one-request screenshot API. It accepts cookie banners and removes 60+ known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, with X-Page-Verdict and X-Billed headers identifying the result. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
See the ScreenshotNeo API docs for options.
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}`);
1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
10. FAQ
Does Java Playwright require Node.js?
No. The Java client runs in your Java build; install its version-matched browsers.
Can one suite cover all three engines?
Yes. Parameterize the browser and keep engine-specific expectations explicit.
When should I use an API instead of Playwright?
Use Playwright for interaction and assertions; use ScreenshotNeo for repeatable image or PDF capture without maintaining browsers.
What Java versions are supported?
The introduction documents Java 8 or higher; verify the current support table before standardizing a newer runtime.


