Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

3 Ways to Use AI to Auto-Generate Playwright Locators (and Check Them)

AI can draft Playwright locators quickly, but only a checked locator is useful. Three workflows, built on Playwright's codegen and Pick Locator tools, with the verification steps that matter.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An AI assistant can draft a Playwright locator in seconds, but a draft is only useful after it has been checked against the live page. The approach below uses AI in the drafting step and keeps Playwright’s documented locator rules as the test. It is a workflow built on Playwright’s official guidance, not a benchmarked method, and the examples are illustrative rather than recorded results.

Start with Playwright’s built-in generator

Playwright ships its own tool for proposing locators from a running page. The official documentation describes it as a code generator. It does not describe it as an AI feature, so treat it as the baseline that any AI suggestion should be compared against. The generator prioritizes role, text, and test ID locators when it proposes a selector.

As an Amazon Associate I earn from qualifying purchases.

Get a candidate from a live page

  1. Open a terminal in your Playwright project and run npx playwright codegen https://example.com, replacing the URL with the page you are testing. A browser window and the Playwright Inspector open.
  2. In the Inspector, click Stop recording so you are no longer recording actions.
  3. Select Pick Locator, then hover over page elements. The Inspector previews the locator for each element under the cursor.
  4. Click the element you want. The locator appears in the Inspector, where you can edit and copy it.

Playwright’s Locators documentation puts it plainly: use the code generator to generate a locator, and then edit it as you’d like. The three approaches below are about how to do that editing with an AI assistant, and how to verify the result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Way 1: Ask AI to rewrite the candidate toward user-facing semantics

The most common output from a live-page picker is a structural selector. It works on the current markup, but it describes the DOM rather than the control a user sees. Give the assistant the generated locator together with the element’s visible text, its role, and any label, then ask for a rewrite that follows Playwright’s preference order.

The rules to put in your prompt are:

  • For buttons, links, checkboxes, and other interactive elements, use getByRole with the accessible name.
  • For form fields, use getByLabel with the associated label.
  • For non-interactive text, use getByText.
  • Use getByTestId only when the team has an explicit test ID contract in the markup.

An illustrative before-and-after looks like this:

// Generated by the picker (structural, breaks when the markup changes)
page.locator('#root > div:nth-child(3) button.btn-primary')

// Rewritten toward the user-facing control
page.getByRole('button', { name: 'Save changes' })

Playwright’s documentation notes that test IDs are resilient to text or role changes but are not user-facing, which is why they belong at the end of the preference order rather than the start.

Way 2: Draft a locator from markup or a description you paste in

When you do not want to run the picker, or the target is inside a state the generator cannot reach easily, you can give the assistant the element’s markup. In Chrome DevTools, open the Elements panel, right-click the node, and choose Copy then Copy element. Paste that HTML into the prompt, along with the page’s expected accessible name and whether the control is a button, link, or form field.

Ask for a candidate that uses the Way 1 preference order and a short explanation of which attribute or text it relies on. Then confirm it in a test, not in your head:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await expect(page.getByRole('button', { name: 'Save changes' })).toHaveCount(1);

The assistant only sees the fragment you pasted. An accessible name can come from aria-labelledby or from other content elsewhere on the page, so a locator that looks right in isolation may not match the rendered name. The count assertion is what catches that.

Way 3: Use AI to check uniqueness and remove positional selectors

Playwright locators are strict for single-target actions. If a locator matches more than one element, the action throws an exception. Many AI-suggested fixes for this problem reach for first(), last(), or nth(), and Playwright’s documentation cautions against using them as a shortcut, because a page change can make the index point at a different element.

Ask the assistant to identify what makes the locator ambiguous and to scope it to a meaningful parent, then refine it with chaining or filters. An illustrative example:

// Ambiguous, and dependent on list position
page.getByRole('button', { name: 'Choose' }).first()

// Scoped to the row that contains the intended plan
page.getByRole('listitem').filter({ hasText: 'Pro plan' })
    .getByRole('button', { name: 'Choose' })

The same review step applies to older CSS or XPath chains. Ask the assistant to replace them with a user-facing locator if one can express the intent. Keep the structural selector only when neither a role, label, text, nor agreed test ID can describe the element.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A checklist before you accept an AI-suggested locator

  • It resolves to exactly one element on the current page, confirmed by a count assertion.
  • Buttons, links, and checkboxes are located by role and accessible name, as a user or assistive technology would perceive them.
  • Form fields are located through their label.
  • It does not depend on first(), last(), or nth() as its only way to disambiguate.
  • It contains no long chain of CSS or XPath steps that mirror the page’s structure.
  • If it uses a test ID, the markup actually carries that attribute and the team has agreed to maintain it.
  • It still passes after the page re-renders, because Playwright resolves locators against the current page when each action runs.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Where AI drafts go wrong

  • The assistant can invent a role or accessible name that does not appear on the page, especially when the markup you pasted is partial.
  • In a list of similar items, it may pick the element that looks most plausible rather than the one your test needs. Scope the locator to the row or region first.
  • A draft generated from a logged-out page can fail on a logged-in page, or from one data state on another. Check the locator in the state your test will actually use.
  • When asked for a “stable” selector, it may return a longer CSS path that is only more specific, not more resilient.

No published study compares AI-drafted locators with hand-written ones, so none of these failure modes should be read as measured frequencies. They are the checks worth running in every case.

“

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.