AI Locators in Playwright



Playwright Training
Playwright Training

AI Locators in Playwright

The idea is to use AI to identify the best locator for an element, rather than manually writing XPath/CSS selectors.

For example, given:

<button class=”btn-primary” data-testid=”login-btn”>

Sign In

</button>

Traditional Playwright:

await page.locator(‘#login-btn’).click();

or preferably:

await page.getByRole(‘button’, { name: ‘Sign In’ }).click();

An AI-assisted locator system could analyze the DOM and determine that:

page.getByRole(‘button’, { name: ‘Sign In’ })

is the most robust locator.

AI Locator Architecture

Flow:

Web Page / DOM

DOM + Accessibility Information

AI / LLM

Analyze Candidate Elements

Rank Locators

Select Best Locator

Playwright Test

What AI can evaluate

An AI locator engine could rank candidates based on:

Locator AI Assessment
getByRole() ⭐⭐⭐⭐⭐
getByLabel() ⭐⭐⭐⭐⭐
getByTestId() ⭐⭐⭐⭐⭐
getByText() ⭐⭐⭐⭐
CSS selector ⭐⭐⭐
XPath ⭐⭐
Dynamic XPath

For example, if the AI sees:

<button

id=”btn_82931″

class=”button primary x7f82″

aria-label=”Submit Order”>

Submit

</button>

It could recommend:

await page.getByRole(‘button’, { name: ‘Submit Order’ }).click();

instead of:

await page.locator(‘#btn_82931’).click();

🔥 More advanced: AI Self-Healing Locators

This becomes even more powerful when combined with your self-healing topic.

Suppose the original test contains:

await page.getByTestId(‘login-button’).click();

The application changes and login-button disappears.

Instead of immediately failing, an AI locator engine can:

  1. Detect locator failure
  2. Inspect the current DOM
  3. Find similar elements
  4. Compare attributes/text/roles
  5. Ask the LLM to identify the replacement
  6. Execute the replacement locator
  7. Record the new locator

Example:

Original Locator

Locator Failed

Capture DOM

AI analyzes candidates

Finds “Sign In” button

getByRole(‘button’, { name: ‘Sign In’ })

Retry Test

Techtutotialz Training, Job support, Interview support
Techtutotialz Training, Job support, Interview support
Tags: , , ,
Leave a comment

Your email address will not be published. Required fields are marked *

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!