Automate Google.com by Playwright

 

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


What You Will Do

  • Launch the browser

  • Open Google

  • Type a search query (example: "Playwright Java")

  • Submit the form

  • Print the titles of search results


 

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.

No comments:

Post a Comment