DEV Community

Cover image for Playwright Locator – Handling Complex UI Elements with Ease
QuangTo
QuangTo

Posted on

Playwright Locator – Handling Complex UI Elements with Ease

As someone working in automation, Playwright has always been my go-to tool for UI testing. It offers a lot of built-in functions that make locating elements efficient and reliable.

That said, many websites out there still use outdated or overly complex DOM structures, which can make it tricky to use standard locator strategies.

In this post, I’d like to share a few practical techniques that have helped me handle these situations more easily(Playwright Codegen couldn't done). Hopefully, they'll save you time and headaches too.

With testId

await page.testId(/^username_login.*facebook(_id)?$/).check()
Enter fullscreen mode Exit fullscreen mode

Example will match

username_login123facebook
username_login4_5facebook_id
Enter fullscreen mode Exit fullscreen mode

With Locator

await page.locator('input[name^="user"][name$="alex"]').check()
Enter fullscreen mode Exit fullscreen mode

this will match:

input class="demo" name="user_7DFDCC4674D94B1_alex"  onclick="UserAction(event)"> 
Enter fullscreen mode Exit fullscreen mode

With visible to prevent strict mode violation

await page.getByRole('button', {name:"Add"}).filter({visible:true}).click()
Enter fullscreen mode Exit fullscreen mode

With Promise

Handle different id, element but having same UI step on scenario, we can try with Promise.

    try {
        await Promise.race([
          page.getByTestId('ctl_personal_q_3_3').check(),
          page.getByTestId('ctl_physician_q_1_0').click(),
          page.locator('#primary_user_q_1_1').selectOption('1')
        ]);
      } catch {
        console.warn('Neither checkbox was found and checked.');
      }
Enter fullscreen mode Exit fullscreen mode

Matching one of many elements

await page.locator('#ctl_gender_id,#gender_user').selectOption('ABC');
Enter fullscreen mode Exit fullscreen mode

Playwright allows us to write short, clean, well-structured code with clear and meaningful naming. If you have any other complex scenario, let share to solve it together

Top comments (0)