Search code examples
playwrightplaywright-testplaywright-typescriptplaywright-java

Playwright automation exception - Page.LocatorOptions().setHasText() giving 2 elements. How to identify uniquely


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.

    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: enter image description here


Solution

  • If you want to use CSS selectors - you can use first()

       page.locator(".mat-option-text", { hasText: "Corporation" }).first()
    

    Another option getByText or getByRole - exact can help

       page.getByRole("option", { name: "Corporation", exact: true })
       // or
       page.getByText("Corporation", { exact: true })
    

    or in Java

       page.getByText("Corporation", new Page.GetByTextOptions().setExact(true)