I am trying to select a value from an Angular dropdown using Playwright-Java. It is failing due to multiple values found. How to uniquely identify by text.
<code> getPage().locator(obj).click();
Locator list = getPage().locator("//span[@class='mat-option-text']", new Page.LocatorOptions().setHasText(value));
list.click();
</code>
<code> getPage().locator(obj).click();
Locator list = getPage().locator("//span[@class='mat-option-text']", new Page.LocatorOptions().setHasText(value));
list.click();
</code>
getPage().locator(obj).click();
Locator list = getPage().locator("//span[@class='mat-option-text']", new Page.LocatorOptions().setHasText(value));
list.click();
Exception: com.microsoft.playwright.PlaywrightException: Error {
message=’Error: strict mode violation: locator(“//span[@class=’mat-option-text’]”).filter(new Locator.FilterOptions().setHasText(“Corporation”)) resolved to 2 elements:
4
If you want to use CSS selectors – you can use first()
<code> page.locator(".mat-option-text", { hasText: "Corporation" }).first()
</code>
<code> page.locator(".mat-option-text", { hasText: "Corporation" }).first()
</code>
page.locator(".mat-option-text", { hasText: "Corporation" }).first()
Another option getByText or getByRole – exact
can help
<code> page.getByRole("option", { name: "Corporation", exact: true })
// or
page.getByText("Corporation", { exact: true })
</code>
<code> page.getByRole("option", { name: "Corporation", exact: true })
// or
page.getByText("Corporation", { exact: true })
</code>
page.getByRole("option", { name: "Corporation", exact: true })
// or
page.getByText("Corporation", { exact: true })
or in Java
<code> page.getByText("Corporation", new Page.GetByTextOptions().setExact(true)
</code>
<code> page.getByText("Corporation", new Page.GetByTextOptions().setExact(true)
</code>
page.getByText("Corporation", new Page.GetByTextOptions().setExact(true)