Comma Selectors in Playwright

 

In Playwright Javacomma selectors refer to compound selectors that use commas , to combine multiple selectors, allowing you to target multiple elements at once — similar to how they work in CSS.


















What Are Comma Selectors?

comma selector allows you to select multiple elements that match any of the selectors separated by a comma.


Syntax:

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




Java Playwright 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 seperated 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();

}
}




Important Points:

  • Comma selectors are useful when you want to interact with multiple possible matching elements.
  • Playwright executes them like CSS, meaning it selects all matching elements.
  • You can still filter using nth()first(), or last().

No comments:

Post a Comment