Automate Google.com by Playwright














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














How to Automate Google Search Using Playwright with Java (Step-by-Step Guide)

Web automation has become an essential skill for testers, developers, and QA engineers. Whether you're validating search functionality, scraping information for testing purposes, or learning browser automation, Playwright with Java offers a modern and powerful solution.

In this complete, SEO-optimized guide, you’ll learn how to automate Google Search using Playwright in Java. We will cover everything from environment setup to interacting with search results, handling dynamic elements, and closing the browser properly.

We will automate the website:

👉 https://www.google.com

Let’s get started.


What is Playwright?

Playwright is an open-source browser automation library developed by Microsoft. It allows you to automate Chromium, Firefox, and WebKit browsers with a single API.

Playwright is widely used for:

  • End-to-end UI testing

  • Web scraping

  • Regression testing

  • Cross-browser automation

  • CI/CD pipeline automation

Unlike traditional automation tools, Playwright offers built-in auto-waiting, fast execution, and strong support for modern web applications.


Why Use Playwright with Java?

Java remains one of the most popular programming languages in enterprise environments. Combining Java with Playwright offers:

  • Strong object-oriented programming structure

  • Easy integration with Maven and Gradle

  • Compatibility with TestNG and JUnit

  • CI/CD pipeline support

  • Scalable test frameworks

If you are transitioning from Selenium to Playwright, you’ll notice faster execution and less flakiness due to Playwright’s intelligent waiting mechanisms.


Step-by-Step Guide to Automating Google.com

Let’s understand the complete automation flow before jumping into code.


1️⃣ Set Up Playwright Environment

Before writing automation code, you must install Playwright in your Java project.

Maven Dependency

Add the following dependency in your pom.xml:

<dependencies> <dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency> </dependencies>

After adding the dependency, run:

mvn clean install

This downloads Playwright libraries and browser binaries.


2️⃣ Launch the Browser

Playwright allows launching browsers in two modes:

  • Headless Mode → No UI (used in CI/CD pipelines)

  • Headed Mode → With UI (used during development/debugging)

Launching a browser ensures a fresh automation session.


3️⃣ Create a Browser Context

A BrowserContext works like an incognito window.

Each context has:

  • Separate cookies

  • Separate cache

  • Separate session data

This ensures isolation between tests.


4️⃣ Navigate to Google.com

You instruct Playwright to open:

https://www.google.com

Playwright automatically waits for the page to load before performing further actions.


5️⃣ Locate the Google Search Box

Google’s search box uses the name attribute:

<input name="q">

Using CSS selector:

[name='q']

Playwright’s locator() API makes it easy to identify elements.


6️⃣ Type a Search Query

Playwright simulates user typing:

  • Fill text

  • Press Enter

  • Trigger search results

For example:

Playwright Java


7️⃣ Interact with Search Results

After pressing Enter:

  • Google dynamically loads results

  • Each result title usually appears under <h3> tags

  • Playwright waits for results before interacting

You can:

  • Extract text

  • Click the first result

  • Validate page titles

  • Count results


8️⃣ Handle Dynamic Behavior

Google search results are dynamic.

Playwright solves synchronization issues using:

  • Auto-waiting

  • waitForSelector()

  • Smart element readiness detection

This reduces flaky test failures.


9️⃣ Perform Additional Actions

You can also automate:

  • Clicking Images tab

  • Clicking News tab

  • Opening links in new tabs

  • Validating URLs

  • Taking screenshots


🔟 Close the Browser

Proper cleanup is essential.

Always close:

  • Browser

  • Context

  • Playwright engine

This prevents memory leaks and resource locking.


Complete Java Code to Automate Google Search

Below is the working example:

import com.microsoft.playwright.*; public class GoogleAutomation { public static void main(String[] args) { // Step 1: Launch Playwright try (Playwright playwright = Playwright.create()) { // Step 2: Launch Chromium browser Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); // Step 3: Create browser context BrowserContext context = browser.newContext(); // Step 4: Open new page Page page = context.newPage(); // Step 5: Navigate to Google page.navigate("https://www.google.com"); // Step 6: Accept cookies (if visible) Locator acceptButton = page.locator( "button:has-text('I agree'), button:has-text('Accept all')"); if (acceptButton.isVisible()) { acceptButton.click(); } // Step 7: Type search query page.locator("[name='q']").fill("Playwright Java"); // Step 8: Press Enter page.keyboard().press("Enter"); // Step 9: Wait for results page.waitForSelector("h3"); System.out.println("Top Search Results:"); for (Locator result : page.locator("h3").all()) { System.out.println(result.textContent()); } // Step 10: Close browser browser.close(); } } }


Code Explanation

StepDescription
Playwright.create()Initializes Playwright engine
chromium().launch()Launches browser instance
browser.newContext()Creates isolated session
page.navigate()Opens Google URL
locator("[name='q']")Finds search input field
keyboard().press("Enter")Submits search
waitForSelector("h3")Waits for results
locator("h3")Extracts result titles


Important Playwright Concepts Used

Locator API

Playwright uses Locator to interact with elements safely and reliably.

Example:

page.locator("h3")

Locators support:

  • CSS selectors

  • XPath

  • Text selectors

  • Role-based selectors


Auto-Waiting Mechanism

Unlike traditional tools, Playwright:

  • Waits for elements to be visible

  • Waits for elements to be enabled

  • Waits for navigation automatically

This reduces flaky automation tests.


Handling Google Cookie Consent

Depending on your region, Google may display:

  • "I agree"

  • "Accept all"

The code handles both using a combined selector:

button:has-text('I agree'), button:has-text('Accept all')

This ensures automation works across different regions.


Enhancing the Automation

You can extend the script to:

1️⃣ Click First Search Result

page.locator("h3").first().click();


2️⃣ Validate Page Title

System.out.println(page.title());


3️⃣ Take Screenshot

page.screenshot(new Page.ScreenshotOptions() .setPath(Paths.get("google.png")));


4️⃣ Run in Headless Mode (CI/CD)

.setHeadless(true)


Best Practices for Playwright Automation

✅ Use BrowserContext for Isolation

Avoid sharing session data between tests.


✅ Use Explicit Waits Only When Necessary

Playwright auto-waits, but you can use:

page.waitForSelector("selector");


✅ Avoid Hardcoded Waits

Do NOT use:

Thread.sleep()

This slows down execution and causes instability.


✅ Close Resources Properly

Always use:

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

This ensures automatic cleanup.


Common Interview Questions

Q1: Why is Playwright better than Selenium?

Playwright provides:

  • Built-in auto-waiting

  • Faster execution

  • Better support for modern JavaScript frameworks

  • Multiple browser support with one API


Q2: What is BrowserContext?

A BrowserContext is like a separate incognito session with isolated cookies and cache.


Q3: Can Playwright handle dynamic websites like Google?

Yes. Playwright’s auto-waiting handles dynamic content loading seamlessly.


Advantages of Automating Google Search

  • Validate search functionality

  • Test SEO results

  • Extract result titles

  • Verify search ranking behavior

  • Learn automation basics with a simple UI

Google search automation is often used as a beginner example because it demonstrates:

  • Input handling

  • Keyboard events

  • Dynamic page loading

  • Result validation


Conclusion

Automating Google search using Playwright with Java is simple, powerful, and efficient. With minimal setup, you can:

  • Launch browsers

  • Interact with UI elements

  • Handle dynamic content

  • Extract data

  • Validate search results

  • Run tests in headless mode

Playwright’s auto-waiting, speed, and reliability make it an excellent choice for modern web automation.

If you’re building a scalable Java automation framework, Playwright is definitely worth adopting.


At a Glance

✔ Install Playwright via Maven
✔ Launch browser (headless or headed)
✔ Create BrowserContext
✔ Navigate to Google
✔ Locate search box
✔ Enter query
✔ Press Enter
✔ Extract results
✔ Close browser


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




















How to Integrate Playwright with TestNG in Java for UI Automation (Complete Guide with Assertions & Example)

Modern web applications demand reliable, scalable, and maintainable automation testing. If you're working with Java and looking for a powerful end-to-end testing solution, combining Playwright with TestNG is one of the most effective approaches available today.

In this detailed, SEO-optimized guide, you’ll learn:

  • What Playwright and TestNG are

  • Why integrating them is beneficial

  • How to configure Maven dependencies

  • How to structure a Playwright + TestNG framework

  • How to write assertions using TestNG

  • How to execute parallel tests

  • Best practices for scalable automation

  • A complete working example using the OrangeHRM demo application

We’ll use the demo website:

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

Let’s dive in.


What is Playwright?

Playwright is a modern open-source browser automation library developed by Microsoft. It supports multiple browsers including:

  • Chromium

  • Firefox

  • WebKit

Playwright provides APIs to:

  • Automate web UI interactions

  • Handle elements dynamically

  • Capture screenshots

  • Perform API testing

  • Run headless or headed browser sessions

  • Execute tests in parallel

Playwright supports multiple programming languages including Java, making it ideal for Java-based automation frameworks.


What is TestNG?

TestNG is a powerful Java testing framework inspired by JUnit and NUnit. It provides advanced testing capabilities such as:

  • Annotations (@Test, @BeforeClass, @AfterClass, etc.)

  • Test grouping

  • Parallel execution

  • Data-driven testing

  • HTML and XML reports

  • Parameterization

When combined with Playwright, TestNG handles test orchestration, while Playwright handles browser automation.


Why Integrate Playwright with TestNG?

Integrating Playwright with TestNG gives you the best of both worlds.

1️⃣ Structured Test Execution

TestNG provides lifecycle annotations like:

  • @BeforeSuite

  • @BeforeClass

  • @Test

  • @AfterClass

This helps you systematically manage browser setup and teardown.


2️⃣ Parallel Execution Support

TestNG allows parallel execution through testng.xml, and Playwright supports multiple independent BrowserContext instances. Together, they allow:

  • Cross-browser testing

  • Parallel test execution

  • Faster build cycles


3️⃣ Built-in Reporting

TestNG automatically generates:

  • HTML reports

  • XML reports

  • Execution summaries

This makes debugging and tracking automation results easy.


4️⃣ Data-Driven Testing

TestNG supports:

  • @DataProvider

  • Parameterized tests

  • External data sources

You can reuse the same Playwright test logic with multiple datasets.


5️⃣ CI/CD Friendly

Both Playwright and TestNG integrate smoothly with:

  • Maven

  • Gradle

  • Jenkins

  • GitHub Actions

  • Azure DevOps

This makes your automation pipeline production-ready.


How Playwright + TestNG Work Together

Let’s understand the integration flow.

Step 1: Add Maven Dependencies

You need both Playwright and TestNG dependencies inside your pom.xml.

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

After adding dependencies, run:

mvn clean install

This downloads all required libraries.


Project Structure Best Practice

A clean structure improves maintainability:

src └── test └── java ├── base │ └── BaseTest.java ├── tests │ └── LoginPageTest.java └── utils
  • BaseTest → Handles browser setup

  • Test classes → Contains actual test cases

  • Utils → Helper methods (optional)


Understanding TestNG Lifecycle with Playwright

Here’s how lifecycle management works:

AnnotationPurpose
@BeforeClassLaunch browser and open page
@TestPerform automation steps
@AfterClassClose browser

This ensures proper setup and teardown for each test class.


Example: Playwright + TestNG Assertions (OrangeHRM Login Page)

We will validate:

  • Page title

  • Login button visibility

  • Login button text

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


Complete LoginPageTest Class

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() { String title = page.title(); Assert.assertTrue(title.contains("OrangeHRM"), "Title does not contain 'OrangeHRM'"); } @Test public void testLoginButtonVisible() { Locator loginButton = page.locator("button[type='submit']"); Assert.assertTrue(loginButton.isVisible(), "Login button is not visible"); } @Test public void testLoginButtonText() { 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 Are We Asserting?

AssertionWhat It Validates
Assert.assertTrue()Condition must be true
Assert.assertEquals()Actual value matches expected
title.contains("OrangeHRM")Page title verification
loginButton.isVisible()UI element visibility
textContent()Inner text validation


Important Playwright Methods for Assertions

MethodPurpose
page.title()Get page title
locator.textContent()Get element text
locator.isVisible()Check visibility
locator.getAttribute()Get attribute value
page.url()Validate URL

These methods fetch data which TestNG then validates.


Running Tests with TestNG XML (Parallel Execution)

Create a testng.xml file:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="PlaywrightSuite" parallel="tests" thread-count="2"> <test name="LoginTests"> <classes> <class name="LoginPageTest"/> </classes> </test> </suite>

This allows:

  • Multiple test classes to run simultaneously

  • Faster execution

  • Better resource usage

Because Playwright uses isolated BrowserContext, tests won’t interfere with each other.


Advantages of Playwright + TestNG Framework

1️⃣ Clean Separation of Responsibilities

  • Playwright → Browser Automation

  • TestNG → Test Management


2️⃣ High Scalability

You can:

  • Add multiple browsers

  • Run parallel tests

  • Execute thousands of test cases


3️⃣ Maintainable Code

Using annotations ensures:

  • Clean setup

  • Reusable methods

  • Easy debugging


4️⃣ CI/CD Ready

You can integrate with:

  • Jenkins

  • Azure DevOps

  • GitHub Actions

Maven makes execution simple:

mvn test


Best Practices for Playwright + TestNG Framework

✅ Use a Base Class

Avoid repeating browser setup in every test class.


✅ Use Explicit Waits When Needed

Although Playwright auto-waits, sometimes use:

page.waitForSelector("selector");


✅ Use Page Object Model (POM)

Separate locators from test logic for better maintainability.


✅ Enable Headless Mode in CI

.setHeadless(true)


✅ Capture Screenshots on Failure

You can use:

page.screenshot();

Integrate this inside TestNG listeners.


Common Interview Questions

Q1: Why use TestNG instead of JUnit?

TestNG supports better parallel execution, parameterization, and grouping.

Q2: Does Playwright support parallel testing?

Yes. Using BrowserContext instances along with TestNG parallel execution.

Q3: Is Playwright better than Selenium?

Playwright provides:

  • Auto-waiting

  • Faster execution

  • Built-in network interception

  • Better modern browser support


Conclusion

Integrating Playwright with TestNG in Java creates a powerful, scalable, and maintainable test automation framework.

You get:

  • Structured test lifecycle management

  • Strong assertion capabilities

  • Parallel execution

  • Built-in reporting

  • CI/CD integration

  • Modern browser automation

By combining Playwright’s powerful browser automation capabilities with TestNG’s structured testing framework, you can build enterprise-level UI automation frameworks that are efficient, reliable, and future-ready.


At a Glance Summary

✔ Use Playwright for browser automation
✔ Use TestNG for test orchestration
✔ Add Maven dependencies
✔ Structure tests using lifecycle annotations
✔ Use TestNG assertions for validation
✔ Configure parallel execution in testng.xml
✔ Integrate with CI/CD


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