Showing posts with label Playwright. Show all posts
Showing posts with label Playwright. Show all posts

Locators in Playwright

 



In Playwright, locators are used to identify and interact with elements on a web page. They are a powerful and reliable way to automate user actions like clicking buttons, entering text, and verifying elements.









What Are Locators in Playwright?

Locators in Playwright abstract away selectors and provide a robust, high-level API to interact with page elements. Rather than manually writing CSS or XPath selectors, locators let you query elements in an expressive and stable way.


Playwright introduces a locator() API that makes element queries lazy and retries actions automatically, reducing flakiness.

Locator button = page.locator("text=Submit");
button.click();  // Retries until the button becomes actionable


Types of Locators in Playwright

Playwright supports several locator strategies:


1. Text Locator

Locates elements that contain specific visible text.

page.locator("text=Login");

2. CSS Selector

Uses standard CSS syntax to locate elements.

page.locator("button.submit");
page.locator("input[type='text']");

3. XPath Selector

Uses XPath expressions for complex DOM querying.

page.locator("xpath=//div[@id='container']");

4. ID Selector

Uses # to select elements by ID (CSS-based).

page.locator("#username");


5. Class Selector

Selects elements by class name.

page.locator(".btn-primary");


6. Attribute Selector

Selects elements by HTML attributes.

page.locator("[placeholder='Search']");
page.locator("[name='email']");


7. Role Locator

Uses ARIA roles for accessibility-based selection.

page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit"));


8. Label Locator

Finds input elements using <label> text.

page.getByLabel("Email");


9. Placeholder Locator

Selects input elements by their placeholder attribute.

page.getByPlaceholder("Search");


10. Alt Text Locator

Used for image elements with alt attributes.

page.getByAltText("Company Logo");


11. Title Locator

Used for elements with title attributes.

page.getByTitle("Help");


12. Test ID Locator

Used when elements have a custom data-testid attribute.

page.getByTestId("login-button");


13. Nth Element Locator

Use .nth(index) to select a specific item in a list of matching elements.

page.locator(".list-item").nth(2).click();  // clicks 3rd item


14. Chained Locators

You can chain locators to scope queries:

Locator form = page.locator("form#login");
form.locator("input[type='password']").fill("secret");


15. Locators with Filters

Use hasTexthas, or hasNotText filters for more control:

page.locator("div", new Locator.LocatorOptions().setHasText("Welcome"));

Here is a Java Playwright example demonstrating different types of locators:
  • Text Locator

  • CSS Selector

  • XPath Selector

  • ID Selector

  • Class Selector



1. Maven Dependency

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


Java Code (LocatorsDemo.java)

import com.microsoft.playwright.*;

public class LocatorsDemo {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Navigate to a demo site (You can replace it with your own test site)
            page.navigate("https://www.saucedemo.com/"); // demo site with multiple selectors

            // 1. Text Locator
            Locator loginButtonByText = page.getByText("Login");
            System.out.println("Text Locator Found: " + loginButtonByText.isVisible());

            // 2. CSS Selector
            Locator usernameByCss = page.locator("input[data-test='username']");
            usernameByCss.fill("standard_user");

            // 3. XPath Selector
            Locator passwordByXpath = page.locator("//input[@id='password']");
            passwordByXpath.fill("secret_sauce");

            // 4. ID Selector
            Locator loginBtnById = page.locator("#login-button");
            loginBtnById.click();

            // 5. Class Selector
            Locator titleByClass = page.locator(".title");
            System.out.println("Title Text: " + titleByClass.textContent());

            browser.close();
        }
    }
}

Output:

Text Locator Found: true
Title Text: Products

Here is Java code using Playwright to demonstrate:

  • Attribute Selector
  • Role Locator
  • Label Locator

import com.microsoft.playwright.*;

public class LocatorExamples {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Navigate to demo site
            page.navigate("https://opensource-demo.orangehrmlive.com/");

            // --- Attribute Selector Example ---
            Locator usernameByAttr = page.locator("input[name='username']");
            usernameByAttr.fill("Admin");

            // --- Role Locator Example ---
            // Here, button with role 'button' and name 'Login'
            Locator loginButton = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Login"));
            // We'll not click yet to keep page on login screen

            // --- Label Locator Example ---
            // Playwright tries to map <label> to its associated input
            Locator passwordByLabel = page.getByLabel("Password");
            passwordByLabel.fill("admin123");

            // Click the login button
            loginButton.click();

            // Wait for some indication of login success
            page.waitForURL("**/dashboard", new Page.WaitForURLOptions().setTimeout(5000));

            System.out.println("Login attempted");
        }
    }
}


Here is Java code using Playwright to demonstrate:

  • Placeholder Locator
  • Alt Text Locator
  • Title Locator


import com.microsoft.playwright.*;

public class LocatorExamples {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            Page page = browser.newPage();

            // Navigate to a demo form page
            page.navigate("https://www.w3schools.com/html/html_forms.asp");

            // --- Placeholder Locator Example ---
            // (Assume placeholder="First name" exists on input field)
            Locator placeholderInput = page.getByPlaceholder("First name");
            placeholderInput.fill("John");

            // --- Alt Text Locator Example ---
            // Go to page with image alt tags
            page.navigate("https://www.w3schools.com/html/html_images.asp");

            // Locate image with alt text
            Locator altImage = page.getByAltText("Girl in a jacket");
            System.out.println("Is Alt Image Visible? " + altImage.isVisible());

            // --- Title Locator Example ---
            // Go to page with title attribute
            page.navigate("https://www.w3schools.com/html/html_tooltip.asp");

            // Locate element by its title attribute
            Locator titleElement = page.getByTitle("I'm a tooltip");
            System.out.println("Title element text: " + titleElement.textContent());

            browser.close();
        }
    }
}


Here is Java code using Playwright to demonstrate:

  • Test ID Locator

import com.microsoft.playwright.*;

public class TestIdLocatorExample {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
      BrowserContext context = browser.newContext();
      Page page = context.newPage();

      // Navigate to the sample website
      page.navigate("https://testing-playground.com/test-id");

      // Use Test ID Locator to find and click the Login button
      Locator loginButton = page.getByTestId("login-button");
      
      // Check visibility and click the button
      if (loginButton.isVisible()) {
        System.out.println("Login button is visible.");
        loginButton.click();
      } else {
        System.out.println("Login button not found.");
      }

      // Optional wait to see result
      page.waitForTimeout(3000);
      
      browser.close();
    }
  }
}


Here is Java code using Playwright to demonstrate:

  • Nth Element Locator

import com.microsoft.playwright.*;

public class NthElementLocatorExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Go to Google
            page.navigate("https://www.google.com");

            // Accept cookies if prompted
            Locator acceptButton = page.locator("button", new Page.LocatorOptions().setHasText("I agree"));
            if (acceptButton.count() > 0) {
                acceptButton.first().click();
            }

            // Enter search query and hit Enter
            page.locator("textarea[name='q']").fill("Playwright Java Tutorial");
            page.keyboard().press("Enter");

            // Wait for results to appear
            page.waitForSelector("h3");

            // Nth Element Locator - Click the 3rd search result (index starts from 0)
            Locator searchResults = page.locator("h3");
            searchResults.nth(2).click();

            // Optional: Wait to observe
            page.waitForTimeout(5000);

            browser.close();
        }
    }
}


Here is Java code using Playwright to demonstrate:

  • Chained Locators
  • Locators with Filters


import com.microsoft.playwright.*;

public class ChainedAndFilterLocators {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Open Swag Labs
            page.navigate("https://www.saucedemo.com/");

            // --- LOGIN ---
            page.locator("#user-name").fill("standard_user");
            page.locator("#password").fill("secret_sauce");
            page.locator("#login-button").click();

            // --- 1. CHAINED LOCATORS ---
            // Example: Find "Add to cart" button for "Sauce Labs Backpack"
            Locator inventoryItem = page.locator(".inventory_item").filter(new Locator.FilterOptions().setHasText("Sauce Labs Backpack"));
            Locator addToCartBtn = inventoryItem.locator("button");
            addToCartBtn.click();
            System.out.println("Added 'Sauce Labs Backpack' to cart using chained locator.");

            // --- 2. LOCATORS WITH FILTERS ---
            // (a) Locate the second inventory item using nth filter
            Locator secondItem = page.locator(".inventory_item").nth(1);
            System.out.println("Second Item Text: " + secondItem.locator(".inventory_item_name").textContent());

            // (b) Locate item with specific text using hasText filter
            Locator bikeLight = page.locator(".inventory_item").filter(
                new Locator.FilterOptions().setHasText("Bike Light")
            );
            bikeLight.locator("button").click();
            System.out.println("Added 'Bike Light' using filter(hasText).");

            // (c) Locate parent based on child (has filter)
            Locator itemWithPrice = page.locator(".inventory_item").filter(
                new Locator.FilterOptions().setHas(page.locator(".inventory_item_price", new Page.LocatorOptions().setHasText("$9.99")))
            );
            System.out.println("Item with price $9.99: " + itemWithPrice.locator(".inventory_item_name").textContent());

            // Keep browser open a bit
            page.waitForTimeout(4000);

            browser.close();
        }
    }
}


Suggested Posts:

1. Locators in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Token Based Authentication in Playwright
5. Basic Authentication in Playwright

Test API using POJO Class in Playwright




1. What is a POJO Class?

  • POJO stands for Plain Old Java Object.
  • It is a simple Java class that does not extend or implement any special framework classes.
  • It is mainly used to define structured data in Java with fields, constructors, getters, and setters.
  • In the context of APIs, POJOs are used to map request and response payloads (usually JSON or XML) into Java objects, making it easier to handle data.
  • Playwright Java supports HTTP requests using the APIRequest module. You can serialize a POJO (Plain Old Java Object) to JSON and send it in the POST request body.

2. Why Use POJO in API Testing?
  • Readable & Maintainable → Instead of writing raw JSON strings, you can work with objects.
  • Reusability → The same POJO class can be used across multiple tests for request/response validation.
  • Serialization/Deserialization → Libraries like Jackson or Gson can automatically convert POJOs to JSON (for requests) and JSON back to POJOs (for responses).
  • Strong Typing → You get compile-time type safety when accessing response fields.


3. How to Test an API with POJO in Playwright Java

Although Playwright is primarily for browser automation, it provides API testing support through its APIRequestContext. Here’s how POJOs fit in:

(1) Define POJO Class

  • Create a POJO representing the request body structure (for POST/PUT).
  • Create another POJO representing the response body structure (for parsing).

(2) Serialize Request POJO to JSON

  • Use Jackson or Gson to convert the Java object (POJO) into JSON format.
  • Pass this JSON as the request body when making API calls with Playwright’s API request methods.

(3) Send API Request with Playwright

  • Use Playwright’s APIRequestContext to send GET, POST, PUT, or DELETE requests.
  • Attach headers, authentication, and the serialized JSON request if needed.

(4) De serialize Response into POJO

  • Playwright will return the response body as JSON.
  • Convert (de serialize) that JSON into a POJO class using Jackson or Gson.

(5) Assertions Using POJO

  • Instead of manually parsing JSON, directly access response fields from the POJO.
  • Example: check if responsePojo.getStatus() equals "success".

4. Advantages of Testing API with POJOs in Playwright Java
  • Cleaner test code → Work with objects, not raw JSON strings.
  • Reusable Models → Same POJO can be used across multiple test cases.
  • Consistency → Ensures request and response structures are strongly validated.
  • Scalability → Easier to expand test coverage as API complexity grows.








Steps

  • Create POJO class to represent your request payload.
  • Initialize Playwright and APIRequestContext.
  • Send POST request using .post() with the serialized POJO.
  • Validate the response.


Example:

Suppose you're testing an API endpoint:


POST https://reqres.in/api/users
Payload: { "name": "Himanshu", "job": "QA Engineer" }


















Maven Dependencies:

<dependencies>
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.44.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>
</dependencies>



1. Create POJO Class

Below is the POJO class consists of two attributes name and job and their getter and setter methods.

public class User {
    private String name;
    private String job;

    public User(String name, String job) {
        this.name = name;
        this.job = job;
    }

    // Getters and setters (optional)
    public String getName() { return name; }
    public String getJob() { return job; }
    public void setName(String name) { this.name = name; }
    public void setJob(String job) { this.job = job; }
}



2. Main Test Code Using Playwright

import com.microsoft.playwright.*;
import com.google.gson.Gson;
import com.microsoft.playwright.options.*;

public class PostApiTest {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            APIRequestContext request = playwright.request().newContext();

            // Create POJO object
            User user = new User("Himanshu", "QA Engineer");

            // Convert POJO to JSON
            Gson gson = new Gson();
            String jsonBody = gson.toJson(user);

            // Send POST request
            APIResponse response = request.post("https://reqres.in/api/users",
                RequestOptions.create()
                    .setHeader("Content-Type", "application/json")
                    .setData(jsonBody)
            );

            // Validate response
            System.out.println("Status: " + response.status());
            System.out.println("Response Body: " + response.text());

            if (response.status() == 201) {
                System.out.println("POST request successful!");
            } else {
                System.out.println("POST request failed!");
            }
        }
    }
}



Code explanation:

(a) Create Playwright Object and APIRequestContext object
(b) Create Pojo class object
(c) Convert POJO to JSON
(d)  Send POST request
(e) Validate the resposne



Expected Output

Status: 201
Response Body: {
  "name": "Himanshu",
  "job": "QA Engineer",
  "id": "734",
  "createdAt": "2025-07-28T10:52:45.108Z"
}
POST request successful!

Above is the output of API with status code 201, as this is POST API and response body in the JSON format.


Important Points:

  • Gson is used to serialize the POJO into JSON.
  • RequestOptions.create().setData(jsonBody) sets the request body.
  • This approach is ideal when working with complex request bodies in APIs.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Basic Authentication in Playwright
5. Token Bsed Authentication in Playwright