Automate Google.com by Playwright

 

To automate https://www.google.com using Playwright with Java, you can perform the following basic steps:


1. Set up Playwright Environment

  • First, you would need to install Playwright and configure it for your preferred programming language (Java, JavaScript/TypeScript, Python, etc.).
  • Playwright provides browsers like Chromium, Firefox, and WebKit, which can be used to open and interact with Google.

2. Launch the Browser
  • Playwright allows launching a browser instance in either headless mode (without GUI) or headed mode (with GUI).
  • For automation, you typically start a new browser session to ensure a clean state.
3. Create a Browser Context
  • A BrowserContext is like a separate user profile, with its own cookies, cache, and session data.
  • Using contexts helps in isolating tests so that actions on one context don’t affect another.
  • For example, if you open Google in one context, it won’t share login data with another context unless you configure it.
4. Navigate to Google.com
  • You instruct Playwright to open the URL https://www.google.com
  • Playwright waits until the page loads and becomes interactive.
5. Locate the Search Box
  • Playwright uses selectors (like CSS selectors, XPath, text selectors) to find elements on a page.
  • The Google search box is a standard input field, so automation involves locating it.
6. Type a Search Query
  • After finding the search box, Playwright can simulate user actions: Typing text into the box (e.g., “Playwright automation”), Adding key presses like Enter to submit the search.
7. Interact with Search Results
  • Once Google displays results, Playwright can: Locate all result links, Click on the first result or verify that certain text is present, Extract text from search results for validation.
8. Handle Dynamic Behavior
  • Google search results often load dynamically, so Playwright’s auto-waiting ensures it waits for elements to be ready before interacting.
  • For example, it won’t try to click a result before the page is fully interactive.
9. Perform Additional Actions
  • You can automate actions beyond just searching: Navigate to the Images or News tab, open links in new tabs, validate page titles or URLs to confirm successful navigation.
10. Close Browser
  • At the end of the automation, Playwright closes the browser or context to free resources.


























Website to be automated: https://www.google.com












Maven Dependencies


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


Java Code to Automate Google Search


import com.microsoft.playwright.*;

public class GoogleAutomation {
    public static void main(String[] args) {
        // Step 1: Launch Playwright and Browser
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));

            // Step 2: Create a new browser context and page
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Step 3: Navigate to Google
            page.navigate("https://www.google.com");

            // Step 4: Accept cookies if visible (optional step depending on location)
            Locator acceptButton = page.locator("button:has-text('I agree'), button:has-text('Accept all')");
            if (acceptButton.isVisible()) {
                acceptButton.click();
            }

            // Step 5: Type a query into the search box
            page.locator("[name='q']").fill("Playwright Java");

            // Step 6: Press Enter to search
            page.keyboard().press("Enter");

            // Step 7: Wait for results to load and print titles
            page.waitForSelector("h3");  // wait for results

            System.out.println("Top Search Results:");
            for (Locator result : page.locator("h3").all()) {
                System.out.println(result.textContent());
            }

            // Step 8: Close browser
            browser.close();
        }
    }
}


Code Explanation:


StepDescription
Playwright.create()Initializes Playwright engine.
browser.newContext()Creates a new browser context (like an incognito window).
page.navigate()Navigates to the URL.
page.locator("[name='q']")Finds the search box on Google using the name attribute.
keyboard().press("Enter")Simulates pressing Enter to submit the form.
locator("h3")Search results on Google usually appear under <h3> tags.


Suggested Posts:

1. BrowserContext in Playwright
2. Automate GET API in Playwright
3. Comma Selectors in Playwright
4. Handle Alerts in Playwright
5. Find Web Elements by XPath in Playwright

Playwright with TestNG Integration


Understanding the Roles

Playwright: Provides APIs to interact with browsers, automate web applications, handle UI elements, and perform end-to-end testing.

TestNG: Provides a testing framework with annotations, test execution flow, grouping, parameterization, parallel execution, and reporting.


Why Integrate Playwright with TestNG?

  • To run Playwright tests in a structured test framework.
  • To leverage TestNG’s annotations like @BeforeSuite, @BeforeTest, @Test, @AfterTest, etc., which make setup and teardown of Playwright objects systematic.
  • To achieve parallel test execution across browsers or test cases using TestNG’s parallel execution support.
  • To generate detailed reports (HTML/XML) of test execution.
  • To allow data-driven testing with TestNG’s parameterization features.

Integration Flow

(1) Dependencies: Add required dependencies (Playwright for browser                          automation, TestNG for test framework).

(2) Base Setup: 
  • Create a base test class where Playwright components (Browser,       BrowserContext, Page) are initialized and cleaned up.
  • Use TestNG lifecycle annotations (@BeforeClass, @AfterClass) for setup/teardown.
(3) Test Structure:
  • Each TestNG test method (@Test) contains the actual Playwright steps (like navigating, clicking, assertions).
  • Tests can be grouped, prioritized, or parameterized through TestNG features.
(4) Parallel Execution:
  • TestNG XML configuration (testng.xml) can be used to define suites, parallel execution, and parameters.
  • This enables multiple browsers or test cases to run in parallel using Playwright’s independent BrowserContext.
(5) Reports & Logs:
  • TestNG automatically generates reports showing passed/failed/skipped test cases.
  • Logs can be captured to debug Playwright test failures.

Benefits
  • Separation of Concerns: Playwright handles automation, TestNG manages test orchestration.
  • Scalability: Easy to scale test execution by combining TestNG parallelism with Playwright’s multiple browser instances.
  • Maintainability: Test code is organized into test classes and methods, improving readability and reusability.
  • Integration: Can be easily plugged into CI/CD pipelines since both TestNG and Playwright are well-supported with Maven/Gradle and Jenkins.


To assert in Playwright with Java using TestNG, we need to:

  • Set up a Playwright project with Java.
  • Use TestNG as the testing framework.
  • Write assertions using TestNG's Assert class.
  • Use Playwright's Locator API to find elements and retrieve text/attributes for validation.




























Website to be automated:

https://opensource-demo.orangehrmlive.com/web/index.php/auth/login
















Step-by-step Explanation

1. Maven Dependencies

<dependencies>
  <!-- Playwright Java -->
  <dependency>
    <groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.44.0</version> <!-- or latest --> </dependency> <!-- TestNG --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.8.0</version> <scope>test</scope> </dependency> </dependencies>



2. Example: Playwright + TestNG Assertion Code

We'll test the title and login button visibility on OrangeHRM login page. below is the LoginPageTest class implemented by Playwright java and TestNG. 

@BeforeClass annotation is used on setUp() to setup things like initialization of browser and launching the url.

@Test annotation is used below to check the title in first test case and submit button is visible or not, in second test case.

@AfterClass annotation is used to close browser and playwright objects.


import com.microsoft.playwright.*;
import org.testng.Assert;
import org.testng.annotations.*;

public class LoginPageTest {
    Playwright playwright;
    Browser browser;
    BrowserContext context;
    Page page;

    @BeforeClass
    public void setUp() {
        playwright = Playwright.create();
        browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
        context = browser.newContext();
        page = context.newPage();
        page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
    }

    @Test
    public void testTitle() {
        // Assertion using TestNG: Check if title contains "OrangeHRM"
        String title = page.title();
        Assert.assertTrue(title.contains("OrangeHRM"), "Title does not contain 'OrangeHRM'");
    }

    @Test
    public void testLoginButtonVisible() {
        // Check if login button is visible
        Locator loginButton = page.locator("button[type='submit']");
        Assert.assertTrue(loginButton.isVisible(), "Login button is not visible");
    }

    @Test
    public void testLoginButtonText() {
        // Check login button text
        Locator loginButton = page.locator("button[type='submit']");
        String buttonText = loginButton.textContent().trim();
        Assert.assertEquals(buttonText, "Login", "Login button text mismatch");
    }

    @AfterClass
    public void tearDown() {
        browser.close();
        playwright.close();
    }
}



What We are Asserting:

AssertionWhat it Validates
Assert.assertTrue(condition)Validates a condition is true
Assert.assertEquals(actual, expected)Compares actual vs expected values
loginButton.isVisible()Checks if the button is rendered and visible
title.contains("OrangeHRM")Checks if title contains expected text



Useful Playwright Methods for Assertion

Playwright MethodUse
page.title()Get page title
locator.textContent()Get inner text of element
locator.isVisible()Check if element is visible
locator.getAttribute("attr")Get attribute value



At a Glance:
  • Use TestNG's Assert class for assertions
  • Fetch values using Playwright (title, text, attributes).
  • Structure tests with @Test@BeforeClass@AfterClass.
  • Combine the power of Playwright automation and TestNG assertions for full UI validation.


Suggested Posts:

1. BrowserContext in Playwright
2. Automate GET API in Playwright
3. Automate POST API in Playwright
4. Handle Alerts in Playwright
5. How to Show Visible Elements in Playwright