1

There are two buttons both with Login as inner text

<div>
      <h3>
        Log in by Email
      </h3>
      <hr />
      Email: <input type="text" name="email"/>
      <button type="submit">
        Login
      </button>
      <h3>
        Log in by something else...
      </h3>
      <button type="submit">
        Login
      </button>
    </div>

I'm trying to click the login button next to the email input field

const login = await page.locator('button',{hasText:'Login'})
await login.click()

And it returns error:

locator.click: Error: strict mode violation: "button >> :scope:has-text("Login")" resolved to 2 elements:
        1) <button type="submit">Login</button> aka playwright.$("text=Login >> nth=1")
        2) <button type="submit">Login</button> aka playwright.$("text=Login >> nth=3")

I want to ask how can I locate the exact button while they both have the same text. Thank you

Clara Lee
  • 35
  • 6

1 Answers1

3

See if this works. You can select elements based on the layout.

const btnLogin = await page.locator('button:has-text("Login"):near(input[name="email"])')
await btnLogin.click()

select button with text "Login" near input field with name "email"

itronic1990
  • 1,231
  • 2
  • 4
  • 18
  • Thank you, it works. although not sure why it failed for chrome browser, it passed after I add .nth(0). – Clara Lee Sep 08 '22 at 14:12