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()
Example will match
username_login123facebook
username_login4_5facebook_id
With Locator
await page.locator('input[name^="user"][name$="alex"]').check()
this will match:
input class="demo" name="user_7DFDCC4674D94B1_alex" onclick="UserAction(event)">
With visible to prevent strict mode violation
await page.getByRole('button', {name:"Add"}).filter({visible:true}).click()
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.');
}
Matching one of many elements
await page.locator('#ctl_gender_id,#gender_user').selectOption('ABC');
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)