First Playwright Script in Java

  

Prerequisites for writing playwright script in java


Before writing the script, ensure you have:

  • Java installed (JDK 11 or above)
  • Maven or Gradle project setup
  • Playwright for Java dependency added



















Step 1: Maven Dependency


<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.45.0</version> <!-- Use the latest available version -->
    </dependency>
</dependencies>


Step 2: Basic Playwright Script in Java

Let's create a file called FirstPlaywrightTest.java:


import com.microsoft.playwright.*;

public class FirstPlaywrightTest {
    public static void main(String[] args) {
        // 1. Launch Playwright
        try (Playwright playwright = Playwright.create()) {

            // 2. Launch a browser (Chromium in this case)
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // 3. Open a new browser context (like a clean browser profile)
            BrowserContext context = browser.newContext();

            // 4. Create a new page/tab in the browser
            Page page = context.newPage();

            // 5. Navigate to the desired URL
            page.navigate("https://example.com");

            // 6. Fetch the page title
            String title = page.title();
            System.out.println("Page title is: " + title);

            // 7. Close the browser
            browser.close();
        }
    }
}




Detailed Explanation


LineCodeExplanation
1import com.microsoft.playwright.*;Imports all Playwright Java classes.
5Playwright.create()Initializes Playwright engine. Must be closed after use.
8playwright.chromium().launch(...)Launches Chromium browser (similar to Chrome). You can also use .firefox() or .webkit().
11browser.newContext()Creates an isolated browser context (like incognito). Useful for running multiple tests.
14context.newPage()Opens a new tab (page) in the browser.
17page.navigate(...)Loads the given URL in the browser.
20page.title()Returns the page’s title.
23browser.close()Gracefully shuts down the browser.



How to run in Eclipse:

Right Click > Run As > Java Application

No comments:

Post a Comment