Playwright Java Examples: Practical Automation Scripts for Beginners (2026)

1. Introduction

Learning browser automation becomes easier when you practise with real code. Instead of memorising methods, automation testers should understand how to launch a browser, locate elements, interact with web pages, verify results, and handle common browser events.

These playwright java examples demonstrate practical web testing tasks using the official Playwright Java library. You will learn how to create automated test scripts, validate application behaviour, and build a foundation for regression testing.

Playwright supports Chromium, Firefox, and WebKit through a consistent API. It also includes features such as automatic waiting for actions, browser contexts, screenshots, and tracing.

One important distinction: Playwright Java is a browser automation library, not Playwright Test. Playwright Test is the JavaScript/TypeScript test runner. Java projects commonly integrate Playwright with JUnit or TestNG to organise and execute tests.

2. Prerequisites and Project Setup

Before running these Playwright Java examples, install:

  • Java Development Kit (JDK 17 recommended for this tutorial)
  • Apache Maven
  • IntelliJ IDEA or Eclipse
  • Basic Java and HTML knowledge
  • Internet access for downloading dependencies and browsers

Add the Playwright dependency

Create a Maven project and add the following dependency to pom.xml. This tutorial uses Playwright Java 1.64.0.

<dependencies>

    <dependency>

        <groupId>com.microsoft.playwright</groupId>

        <artifactId>playwright</artifactId>

        <version>1.64.0</version>

    </dependency>

    <dependency>

        <groupId>org.junit.jupiter</groupId>

        <artifactId>junit-jupiter</artifactId>

        <version>5.11.4</version>

        <scope>test</scope>

    </dependency>

</dependencies>

<build>

    <plugins>

        <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-surefire-plugin</artifactId>

            <version>3.5.2</version>

        </plugin>

    </plugins>

</build>

Maven downloads the Java library and its dependencies. Next, install the browser binaries supported by your Playwright version:

mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args=”install”

For Linux CI environments, you may need browser system dependencies as well:

mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args=”install –with-deps chromium”

A simple project structure is:

playwright-java-examples/

├── pom.xml

└── src/

    ├── main/java/examples/

    │   └── FirstExample.java

    └── test/java/tests/

        └── LoginTest.java

3. First Playwright Java Example: Launch a Browser

Start with a small program that launches Chromium, opens a website, and retrieves its title.

package examples;

import com.microsoft.playwright.*;

public class FirstExample {

    public static void main(String[] args) {

        try (Playwright playwright = Playwright.create()) {

            Browser browser = playwright.chromium().launch(

                new BrowserType.LaunchOptions()

                    .setHeadless(false)

            );

            Page page = browser.newPage();

            page.navigate(“https://playwright.dev/”);

            System.out.println(“Page title: ” + page.title());

            System.out.println(“Current URL: ” + page.url());

            browser.close();

        }

    }

}

How it works:

  1. Playwright.create() creates the Playwright instance.
  2. chromium().launch() starts the Chromium browser.
  3. newPage() creates a browser page.
  4. navigate() opens the requested URL.
  5. title() and url() retrieve page information.

The setHeadless(false) option displays the browser window. Remove it or set it to true for headless execution.

Expected result: The browser opens the Playwright website, and the console prints its page title and URL.

4. Playwright Java Locator Examples

Locators identify elements on a web page. Prefer accessible locators such as roles and labels because they usually represent how users interact with an application.

Assume the page contains a login form with a username field, password field, and Login button.

Role locator

page.getByRole(

    AriaRole.BUTTON,

    new Page.GetByRoleOptions().setName(“Login”)

).click();

This locates a button by its accessible role and name.

Text locator

page.getByText(“Welcome to Dashboard”).click();

Use this when the visible text identifies the target element.

Label locator

page.getByLabel(“Email”).fill(“tester@example.com”);

This works well when form controls have properly associated labels.

Placeholder locator

page.getByPlaceholder(“Enter your password”).fill(“Test@123”);

This identifies an input using its placeholder text.

CSS locator

page.locator(“#username”).fill(“admin”);

page.locator(“.submit-button”).click();

CSS selectors are useful when an application exposes stable IDs or classes.

XPath locator

page.locator(“//button[@type=’submit’]”).click();

XPath can locate elements through attributes and DOM relationships. However, avoid unnecessarily complex XPath expressions because page structure changes can make them fragile.

LocatorExampleRecommended use
RolegetByRole()Buttons, links, headings
TextgetByText()Visible text
LabelgetByLabel()Form fields
PlaceholdergetByPlaceholder()Inputs with placeholders
CSSlocator(“#id”)Stable selectors
XPathlocator(“//…”)Specific DOM relationships

5. Playwright Java Browser Interaction Examples

Browser automation involves more than opening pages. Testers must interact with forms, controls, menus, and files.

Click and fill

page.navigate(“https://example.com/login”);

page.locator(“#email”).fill(“admin@example.com”);

page.locator(“#password”).fill(“Admin@123”);

page.locator(“button[type=’submit’]”).click();

The fill() method replaces the existing input value. Use click() to interact with buttons, links, and other clickable elements.

Checkbox

page.locator(“#rememberMe”).check();

boolean selected = page.locator(“#rememberMe”).isChecked();

System.out.println(“Checkbox selected: ” + selected);

Use uncheck() when the test needs to clear a selected checkbox.

Dropdown

page.locator(“#country”).selectOption(“IN”);

The value IN must match an option value in the dropdown. You can also select by label:

page.locator(“#country”).selectOption(

    new SelectOption().setLabel(“India”)

);

Keyboard interaction

page.locator(“#search”).fill(“Playwright Java”);

page.keyboard().press(“Enter”);

This example enters a search term and presses Enter.

File upload

import java.nio.file.Paths;

page.locator(“input[type=’file’]”).setInputFiles(

    Paths.get(“src/test/resources/sample.pdf”)

);

The file path must exist on the machine running the test. For multiple files, pass an array of paths to setInputFiles().

6. Playwright Java Assertion Examples

Assertions verify whether an application behaves as expected. For simple checks, JUnit assertions work well with Playwright Java.

import static org.junit.jupiter.api.Assertions.*;

assertEquals(“Example Domain”, page.title());

assertTrue(page.url().contains(“example.com”));

For element verification, use Playwright’s web-first assertions. They retry until the expected condition is satisfied or the timeout expires.

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

assertThat(page.locator(“h1”)).isVisible();

assertThat(page.locator(“h1”)).hasText(“Welcome”);

You can also verify a button or link:

assertThat(

    page.getByRole(

        AriaRole.BUTTON,

        new Page.GetByRoleOptions().setName(“Submit”)

    )

).isEnabled();

Important: A web-first assertion such as assertThat(locator).isVisible() waits and retries. In contrast, isVisible() returns the current visibility state immediately. Choose the method that matches your test requirement.

7. Handling Alerts and Frames

Some web applications use JavaScript dialogs such as alerts, confirmations, and prompts.

Handle an alert

Register a dialog handler before performing the action that triggers the alert.

page.onDialog(dialog -> {

    System.out.println(“Dialog message: ” + dialog.message());

    dialog.accept();

});

page.getByText(“Show Alert”).click();

Use dialog.dismiss() to cancel a dialog. For prompt dialogs, dialog.accept(“your text”) can provide a response.

Work with an iframe

An iframe contains a separate document embedded in the page. Use frameLocator() to interact with its elements.

page.navigate(“https://example.com”);

Locator frameInput = page.frameLocator(“#payment-frame”)

                          .locator(“#cardNumber”);

frameInput.fill(“4111111111111111”);

Replace the URL and selectors with those from your application. The iframe selector must identify the correct frame.

8. Screenshot and Browser Context Examples

Screenshots help investigate failed tests and document application behaviour.

Capture a screenshot

import java.nio.file.Paths;

page.screenshot(

    new Page.ScreenshotOptions()

        .setPath(Paths.get(“screenshots/homepage.png”))

        .setFullPage(true)

);

Create the screenshots directory before saving the file.

Create an isolated browser context

A browser context provides an isolated browser session. Separate contexts help prevent cookies and local storage from one test affecting another.

BrowserContext context = browser.newContext();

Page page1 = context.newPage();

page1.navigate(“https://example.com”);

BrowserContext anotherContext = browser.newContext();

Page page2 = anotherContext.newPage();

page2.navigate(“https://example.com”);

Each context has its own session state. Close contexts after use, and close the browser when the test suite finishes.

9. Real-World Login Test Using Reusable Java Code

A login test is a common automation use case. The following example uses a reusable method so the same login steps can be called by multiple tests.

package examples;

import com.microsoft.playwright.*;

public class LoginExample {

    public static void login(Page page, String email, String password) {

        page.navigate(“https://your-test-app.example/login”);

        page.locator(“#email”).fill(email);

        page.locator(“#password”).fill(password);

        page.getByRole(

            AriaRole.BUTTON,

            new Page.GetByRoleOptions().setName(“Login”)

        ).click();

    }

    public static void main(String[] args) {

        try (Playwright playwright = Playwright.create()) {

            Browser browser = playwright.chromium().launch();

            BrowserContext context = browser.newContext();

            Page page = context.newPage();

            login(page, “tester@example.com”, “Test@123”);

            System.out.println(“After login URL: ” + page.url());

            context.close();

            browser.close();

        }

    }

}

Replace the example URL and selectors with those from your test application. In a real project, verify a reliable post-login element or dashboard heading rather than relying only on the URL.

For a larger application, move login actions into a LoginPage Page Object class. This keeps selectors and page behaviour separate from test logic. Read our guide to Playwright Java Page Object Model when building reusable test components.

10. Integrate Playwright Java with JUnit 5

JUnit provides annotations and assertions to organise automated test scripts. Playwright Java does not include Playwright Test, so Java developers use a Java test framework such as JUnit or TestNG.

Here is a complete basic JUnit test:

package tests;

import com.microsoft.playwright.*;

import org.junit.jupiter.api.*;

import static org.junit.jupiter.api.Assertions.*;

class HomePageTest {

    Playwright playwright;

    Browser browser;

    Page page;

    @BeforeEach

    void setUp() {

        playwright = Playwright.create();

        browser = playwright.chromium().launch();

        page = browser.newPage();

    }

    @Test

    void verifyHomePageTitle() {

        page.navigate(“https://playwright.dev/”);

        assertTrue(page.title().contains(“Playwright”));

        assertTrue(page.url().contains(“playwright.dev”));

    }

    @AfterEach

    void tearDown() {

        if (browser != null) browser.close();

        if (playwright != null) playwright.close();

    }

}

Run the test from your project directory:

mvn clean test

JUnit executes the test method, while @BeforeEach prepares the browser and @AfterEach closes the resources. The Maven Surefire plugin stores test reports under target/surefire-reports.

For larger suites, consider a shared test base, configuration files, Page Objects, test data management, and separate browser contexts. Explore Playwright Java JUnit Integration and Playwright Java TestNG Integration for more examples.

11. Common Errors and Best Practices

Common problemLikely reasonRecommended solution
Browser executable missingBrowser binaries not installedRun the Playwright install command
Element not foundIncorrect or unstable selectorInspect the page and prefer role or label locators
Test times outElement is unavailable or action is blockedCheck the selector, page state, and network
Upload failsFile path is incorrectUse an existing absolute or project-relative path
Tests affect each otherShared session stateUse separate browser contexts
Browser remains openResources not closedClose context, browser, and Playwright

Follow these practices when writing Playwright Java scripts:

  1. Prefer role, label, and other user-facing locators over fragile selectors.
  2. Avoid fixed Thread.sleep() calls. Playwright automatically waits for actionability conditions, and web-first assertions retry.
  3. Use explicit assertions to verify application behaviour.
  4. Create isolated contexts for independent test sessions.
  5. Close browser resources in cleanup methods or try-with-resources blocks.
  6. Keep credentials and environment-specific URLs outside source code.
  7. Capture screenshots or traces when debugging difficult failures.
  8. Keep tests independent so they can run reliably in regression suites.

For a scalable design, read the Playwright Framework Design guide.

12. Playwright Java Interview Questions and FAQs

Practical interview questions

1. What is Playwright Java?

It is Microsoft’s Java library for automating browsers such as Chromium, Firefox, and WebKit.

2. What is the difference between Playwright Java and Playwright Test?

Playwright Java is a Java browser automation library. Playwright Test is a test runner designed for JavaScript and TypeScript.

3. How do you launch Chromium in Java?

Use Playwright.create() followed by playwright.chromium().launch().

4. What is a BrowserContext?

It is an isolated browser session with separate cookies, local storage, and session state.

5. How do you handle dropdowns?

Use selectOption() on the dropdown locator.

6. How do you upload a file?

Use setInputFiles() with a valid file path.

7. How do you handle JavaScript alerts?

Register a page.onDialog() handler and call accept() or dismiss().

8. Why should you avoid Thread.sleep()?

Fixed delays slow down tests and can still fail when an application takes longer than expected. Prefer Playwright’s automatic waiting and retrying assertions.

Frequently asked questions

Is Playwright Java examples suitable for beginners?

Yes. Beginners who know basic Java can start with browser launch, navigation, locators, and simple interactions. Practise each example before moving to Page Objects and test framework integration.

How do I get started with Playwright Java examples?

Install Java and Maven, create a Maven project, add the Playwright dependency, install browser binaries, and run a small Java program. Then practise locators, assertions, and form interactions.

What is Playwright Java examples?

The phrase refers to practical Java code samples that demonstrate browser automation using the Playwright Java library. Examples include clicking buttons, filling forms, handling frames, capturing screenshots, and validating page content.

Leave a Comment

Your email address will not be published. Required fields are marked *