1

First off, I want to tell you that I am new to this playwright tool. My problem is, I have two option male and female when I try to click male option in the list using the following code,

page.getByRole(AriaRole.LISTITEM).filter(new Locator.FilterOptions().setHasText("Male")).click();

it throws the following error

Exception in thread "main" com.microsoft.playwright.PlaywrightException: Error {
  message='Error: strict mode violation: getByRole(AriaRole.LISTITEM).filter(new Locator.FilterOptions().setHasText("Male")) resolved to 2 elements:
    1) <li id="cP1Q100" class="z-comboitem">…</li> aka getByRole(AriaRole.LISTITEM).filter(new Locator.FilterOptions().setHasText("Female"))
    2) <li id="cP1Q200" class="z-comboitem z-comboitem-sele…>…</li> aka getByRole(AriaRole.LISTITEM).filter(new Locator.FilterOptions().setHasText("Male"))

This happens because male is the substring of female. If I try to click the female option it happens without having any problem because female is unique here. How can I resolve this problem? I am using Java Playwright.

Rajagopalan
  • 5,465
  • 2
  • 11
  • 29

3 Answers3

1

In JavaScript you use nth(index) method.

await page.locator('//button').nth(index).click();
Mohamed Sajjadh
  • 139
  • 2
  • 11
0

You may wanna try to use RegEx. And Pattern in Java, I believe it's case sensitive by default, while text is not.

page.getByRole(AriaRole.LISTITEM)
  .filter(new Locator.FilterOptions().setHasText(Pattern.compile("Male"))).click();

https://playwright.dev/java/docs/locators#filtering-locators

unickq
  • 1,497
  • 12
  • 18
0

I came across this same problem and it appears that playwright searches for substrings by default. To match text exactly, use the exact parameter as described here.