Playwright Java Maven Setup and Browser Installation
In this article
Using Playwright with Java and Maven allows you to automate modern web applications across Chromium, Firefox, and WebKit using a single API. This setup enables fast, reliable end-to-end testing with features like auto-waiting, network interception, and headless execution. By integrating Playwright into a Maven project, you can manage dependencies efficiently and integrate your tests into CI/CD pipelines seamlessly.
What You'll Need
- Java Development Kit (JDK) 8 or higher installed on your system.
- Apache Maven installed and configured in your system PATH.
- An Integrated Development Environment (IDE) such as IntelliJ IDEA, Eclipse, or VS Code.
- An active internet connection to download the Playwright library and browser binaries.
Step-by-Step
- Create a New Maven Project: Open your IDE and create a new Maven project. If you are using the command line, you can run
mvn archetype:generateto create a basic project structure. Ensure yourpom.xmlis initialized correctly. - Add Playwright Dependency: Open your
pom.xmlfile and add the Playwright dependency within the<dependencies>section. This tells Maven to download the necessary Java libraries to interact with the Playwright engine.
Note: Check the Maven Central Repository for the latest stable version.<dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.40.0</version> </dependency> - Import Changes: In your IDE, trigger a Maven reload (e.g., right-click the project and select Maven > Reload Project in IntelliJ) to download the Playwright JAR files.
- Install Browser Binaries: Playwright does not use the browsers already installed on your computer; it requires specific patched versions of Chromium, Firefox, and WebKit. To install these, you can run the following command in your terminal from the project root:
Alternatively, Playwright will automatically attempt to download browsers the first time you run a script, provided the environment has the necessary permissions.mvn exec:java -e -Dexec.mainClass="com.microsoft.playwright.CLI" -Dexec.args="install" - Create a Sample Test Class: Create a new Java class (e.g.,
PlaywrightTest.java) in yoursrc/test/javadirectory. - Implement the Sample Code: Copy and paste the following code to verify the installation. This script launches a browser, navigates to a page, and takes a screenshot.
import com.microsoft.playwright.*; public class PlaywrightTest { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { // Launch browser (set setHeadless(false) to see the browser window) Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false)); BrowserContext context = browser.newContext(); Page page = context.newPage(); // Navigate to a URL page.navigate("https://playwright.dev"); // Print the page title System.out.println("Page Title: " + page.title()); // Take a screenshot page.screenshot(new Page.ScreenshotOptions().setPath(java.nio.file.Paths.get("example.png"))); browser.close(); } } } - Run the Code: Execute the
mainmethod of your class. If configured correctly, a Chromium window will open, navigate to the Playwright website, and save a file namedexample.pngin your project directory.
Common Mistakes
- Forgetting Browser Installation: Many users assume Playwright uses the Chrome browser installed on their OS. If you skip the
installcommand, the code will throw an exception stating that the browser executable was not found. - Incorrect JDK Version: Using a JDK version older than 8 will lead to compilation errors as Playwright relies on modern Java features.
- Ignoring Try-with-Resources: Failing to wrap
Playwright.create()in a try-with-resources block or failing to call.close()on the browser can lead to memory leaks and zombie browser processes remaining active in the background. - Hardcoding Paths: Using absolute file paths for screenshots or downloads that only work on one operating system, making the tests fail in CI/CD environments.
Tips
- Use Headless Mode for CI: While
setHeadless(false)is great for debugging, always set it totrue(the default) in your Jenkins, GitHub Actions, or GitLab CI pipelines to save resources and avoid errors related to missing display drivers. - Leverage BrowserContext: Instead of creating a new browser for every test, create one browser instance and use
browser.newContext()for each test. This provides isolated environments (cookies, local storage) and is significantly faster. - Use the Codegen Tool: Playwright includes a code generator that records your actions in the browser and writes the Java code for you. Run
mvn exec:java -e -Dexec.mainClass="com.microsoft.playwright.CLI" -Dexec.args="codegen"to start recording. - SlowMo Option: When debugging, use
setSlowMo(100)inLaunchOptionsto slow down Playwright's operations by a specified number of milliseconds, making it easier to follow the execution visually.
Troubleshooting
If you encounter issues, start by checking the following areas:
- Browser Installation Failures: If the
installcommand fails, ensure your firewall or corporate proxy is not blocking downloads from the Playwright CDN. You may need to configure Maven proxy settings insettings.xml. - Dependency Conflicts: If you see
ClassNotFoundExceptionorNoClassDefFoundError, runmvn clean installto ensure all dependencies are properly downloaded and the project is built from scratch. - Linux Dependency Issues: On Linux (especially Ubuntu), Playwright browsers may require additional system libraries. Run the command
mvn exec:java -e -Dexec.mainClass="com.microsoft.playwright.CLI" -Dexec.args="install-deps"to install the necessary OS-level dependencies. - Timeout Errors: If tests fail with
TimeoutError, check if the element you are searching for is inside an iframe or a shadow DOM, as these require specific handling in Playwright.
Frequently Asked Questions
Does Playwright support all major browsers?
Yes, Playwright supports Chromium (Chrome, Edge), Firefox, and WebKit (Safari) using a unified API, allowing you to run the same test across different engines.
How is Playwright different from Selenium?
Playwright offers built-in auto-waiting for elements, faster execution through the CDP (Chrome DevTools Protocol), and better handling of modern web features like shadow DOM and network interception without needing third-party plugins.
Can I run Playwright tests in parallel?
Yes. By using BrowserContext, you can run multiple isolated sessions within a single browser instance, which can be integrated with TestNG or JUnit 5 to execute tests in parallel.
Do I need to install Chrome manually?
No. Playwright downloads its own optimized browser binaries that are guaranteed to work with the version of the library you are using.
How do I handle pop-ups or new tabs?
Playwright handles this via the Page and BrowserContext objects. You can listen for the popup event on the context to capture and interact with newly opened windows.