Showing posts with label Playwright Locators. Show all posts
Showing posts with label Playwright Locators. 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

Comma Selectors in Playwright



Comma Selectors in Playwright Java – Complete Guide with Examples

When working with modern web automation frameworks, flexibility in element selection is extremely important. In Playwright Java, one powerful yet often underused feature is the comma selector. Comma selectors allow you to combine multiple CSS selectors into a single locator, making your automation scripts more efficient, readable, and maintainable.

In this comprehensive guide, you’ll learn:

  • What comma selectors are in Playwright

  • How comma selectors work in Playwright Java

  • Practical real-world use cases

  • Java code examples with explanation

  • Best practices for maintainable test automation

  • SEO-friendly automation insights for testers and developers

If you are learning Playwright automation with Java, this guide will help you write smarter locators and reduce duplication in your test scripts.

























What Are Comma Selectors in Playwright?

In Playwright Java, comma selectors refer to compound CSS selectors separated by commas (,) that allow you to target multiple elements at once.

This works exactly like standard CSS selector grouping.

Basic Syntax

Locator locator = page.locator("selector1, selector2, selector3");

This means:

  • Match all elements that satisfy selector1

  • OR match all elements that satisfy selector2

  • OR match all elements that satisfy selector3

Playwright merges all matching elements into a single Locator collection.

Why Use Comma Selectors in Playwright?

Comma selectors are extremely useful in automation testing when:

  • An element may appear in different formats.

  • UI changes dynamically (mobile vs desktop).

  • Different builds show slightly different element names.

  • You want to perform bulk operations on multiple element types.

Instead of writing separate locators and conditionally handling them, you can combine them in a single line.

This improves:

  • Test readability

  • Code reusability

  • Maintenance

  • Stability of automation scripts


How Comma Selectors Work in Playwright Java

Let’s understand how Playwright evaluates comma selectors step by step.

1. Multiple Selectors in One Locator

When you write:

page.locator("a:has-text('Gmail'), a:has-text('GoogleMail')");

Playwright will:

  • Find all <a> elements containing "Gmail"

  • Find all <a> elements containing "GoogleMail"

  • Combine results into one locator


2. Merging Results

If both selectors match elements, Playwright merges them into a single collection.

You can then:

  • Click

  • Count

  • Assert visibility

  • Extract text

  • Filter using nth(), first(), or last()


3. Works Like CSS

Since Playwright supports CSS selectors, comma selectors follow standard CSS behavior.

Example:

page.locator("h1, h2, h3");

This selects all heading elements from <h1>, <h2>, and <h3>.


Website Example Used in This Guide

We will use:

https://www.google.com/

This example demonstrates how comma selectors work when selecting links like:

  • Gmail

  • Images

  • GoogleMail (if present in some variations)


Complete Java Playwright Example – Comma Selectors

Below is the full working Playwright Java code:

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class CommaSelectorsExample {
    
    public static void main(String[] args) {
        
    // this code will click Gmail or if instead of Gmail GoogleMail is present like or condition
    Playwright playwright = Playwright.create();
    Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
    Page p1 = browser.newPage();
    p1.navigate("https://www.google.co.in");
    p1.locator("a:has-text('Gmail'),a:has-text('GoogleMail') ").click();
    
    //For two links comma separated selector code is there
    Page p2 = browser.newPage();
    p2.navigate("https://www.google.co.in");
    Locator lc = p2.locator("a:has-text('Gmail'),a:has-text('Images') ");
    System.out.println(lc.count());
    
    //click on Gmail by using xpath
    Page p3 = browser.newPage();
    p2.navigate("https://www.google.co.in");
    Locator gmailLocator = p2.locator("//a[text()='Gmail'] | //a[text()='GooleMail'] ");
    System.out.println(gmailLocator.textContent());
    gmailLocator.click();
    
    browser.close();
    playwright.close();

}
}


Code Explanation in Detail

Let’s break the code into simple steps so beginners can clearly understand it.


(a) Launching the Browser

Playwright playwright = Playwright.create(); Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
  • Creates Playwright instance

  • Launches Chromium browser

  • setHeadless(false) allows you to see browser execution


(b) Navigating to the Website

p1.navigate("https://www.google.co.in");

This opens Google homepage.


(c) Using Comma Selector for OR Condition

p1.locator("a:has-text('Gmail'),a:has-text('GoogleMail') ").click();

This means:

  • If "Gmail" link exists → click it

  • If "GoogleMail" exists instead → click it

This behaves like a logical OR condition in automation.


(d) Counting Multiple Elements

Locator lc = p2.locator("a:has-text('Gmail'),a:has-text('Images') "); System.out.println(lc.count());

This counts how many elements match:

  • Gmail

  • Images

If both exist → count = 2
If only one exists → count = 1


(e) XPath Alternative Using Pipe Operator

Locator gmailLocator = p2.locator("//a[text()='Gmail'] | //a[text()='GooleMail'] ");

Here:

  • | works as OR in XPath

  • Similar concept to comma in CSS


Real-World Use Cases of Comma Selectors in Automation

Let’s explore practical automation scenarios.


1. Handling UI Variations

Sometimes in different environments:

  • Dev shows "Submit"

  • QA shows "Continue"

  • Prod shows "Proceed"

Instead of writing separate logic:

page.locator("button:has-text('Submit'), button:has-text('Continue'), button:has-text('Proceed')").click();

This makes your test environment-independent.


2. Mobile vs Desktop Testing

In responsive websites:

  • Desktop: <button>

  • Mobile: <a> styled as button

You can write:

page.locator("button#login, a#login").click();


3. Bulk Heading Validation

Locator headings = page.locator("h1, h2, h3"); System.out.println("Total headings: " + headings.count());

Useful for SEO validation testing.


4. Error Message Validation

Sometimes error messages appear as:

  • <div class="error">

  • <span class="error-text">

You can combine:

page.locator("div.error, span.error-text");


Advantages of Comma Selectors in Playwright

1. Reduces Code Duplication

No need to write multiple locators.

2. Improves Maintainability

One combined selector is easier to update.

3. Cleaner Test Logic

Avoids complex if-else blocks.

4. Flexible for Dynamic UIs

Works well with modern JavaScript-heavy applications.


Important Points to Remember

✔ Comma selectors follow CSS rules.
✔ Playwright returns a merged list of matched elements.
✔ You can filter using .first(), .last(), .nth(index).
✔ Use carefully — too many combined selectors reduce readability.


Best Practices for Using Comma Selectors

To keep your automation framework maintainable:

Use Only When Necessary

Don’t combine unrelated elements.

Keep Selectors Readable

Avoid extremely long comma-separated selectors.

Prefer Unique Identifiers

If possible, use id, data-testid, or stable attributes.

Combine with Assertions

After locating, verify visibility:

Locator element = page.locator("selector1, selector2");
if(element.count() > 0){
    element.first().click();
}


CSS vs XPath – OR Conditions

Selector TypeOR Syntax
CSSselector1, selector2
XPath`//path1

Both achieve similar functionality.

In Playwright Java:

  • CSS is generally faster and cleaner.

  • XPath is useful for complex DOM traversal.


When NOT to Use Comma Selectors

Avoid using them when:

  • Elements are unrelated.

  • You need strict element control.

  • Test clarity is reduced.

Overusing comma selectors can make debugging harder.


Advanced Example – Filtering After Comma Selector

Locator locator = page.locator("button.primary, button.secondary");
locator.filter(new Locator.FilterOptions().setHasText("Submit")).click();

This selects:

  • Either primary or secondary button

  • But only if it contains "Submit"


Summary

Comma selectors in Playwright Java are a powerful way to:

  • Combine multiple element locators

  • Handle dynamic UI changes

  • Reduce duplication

  • Improve automation efficiency

They work exactly like CSS comma-separated selectors and are extremely helpful in real-world automation scenarios.

By using comma selectors wisely, you can create:

  • Stable automation frameworks

  • Clean test cases

  • Scalable test architecture

If you are preparing for automation interviews or building enterprise-level frameworks, mastering comma selectors will give you an edge.



Suggested Posts:

1. Handle IFrames in Playwright
2. Automate Login Page in Playwright
3. Comma Selectors in Playwright
4. Handle Alerts in Playwright
5. Handle Dynamic Webtable in Playwright