playwright

Handle dynamic UI-ID in playwright with locator method?


Trying to select a button with dynamic UI-ID.

await page.locator('#ui-id-4').getByLabel('Add').click(); 
await page.locator('#ui-id-5').getByLabel('Add').click();

Does anyone have a good practice for this? Trying to find suggestions on the official playwright documentation without any good examples.


Solution

  • You may try using ^=, which is starts with in CSS, and then access required element by nth.

    await page.locator("[id^='ui-id-']").nth(YOUR_INDEX).getByLabel('Add').click();