Visual Grounding and Reliable UI Automation

Most automation failures are not dramatic. The agent clicks something slightly wrong, nothing complains, and the work is quietly incorrect.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Reliability comes from four habits: identify elements by what they mean (role, name, label), wait for a state instead of a number of seconds, refuse to guess when more than one thing matches, and verify the outcome in the application, not in the agent's own account of it. Use screen coordinates only when nothing better exists, and check them.

What you will learn: ways to identify elements, visual grounding, a runnable comparison across a redesign, dependable clicks, typing, scrolling and navigation, dynamic pages, long forms and measurement.
Prerequisites: Browser and Computer-Use Agents.

Versions used

The example runs in November 2026 with Python 3.13 and Playwright 1.63.0 in headless Chromium, using the shop.py pages shown on Browser and Computer-Use Agents.

Beginner Pointing at the right thing

Ways to identify an element

MethodExample ideaSurvives a redesign?
Role and accessible namebutton "Add to basket"Usually, while the meaning stays
Label or placeholderfield labeled "Quantity"Usually
Test identifierdata-testid="add"Yes, if your team maintains it
Visible text"Add to basket"Breaks with wording or language changes
CSS class or generated idbutton.primaryOften not
XPath by positionthird div, second buttonRarely
Screen coordinatesclick at (334, 100)No: changes with size, scroll and layout

Playwright's documentation recommends user-facing attributes and explicit contracts such as role locators. These depend on pages being built accessibly, which is one more reason to fix accessibility in your own applications.

See what a redesign does

The same task runs on an old page and a redesigned one. The redesign changes ids and classes, adds a newsletter banner with a similar-looking button and enables "Add to basket" only after a short delay. Run python reliable.py next to shop.py, with Playwright installed as described on Browser and Computer-Use Agents.

"""The same task before and after a redesign, with three ways of finding elements."""
from playwright.sync_api import Error, sync_playwright

import shop

EXPECTED = "Basket: 3 x paper rolls"


def by_css(page):
    page.locator("input[type=number]").fill("3", timeout=1500)
    page.locator("button.primary").click(timeout=1500)


def by_position(page):
    page.locator("input").first.fill("3", timeout=1500)
    box = {"x": 334, "y": 100}          # where the button sat on the old page
    page.mouse.click(box["x"], box["y"])


def by_role(page):
    page.get_by_label("Quantity").fill("3", timeout=1500)
    page.get_by_role("button", name="Add to basket", exact=True).click(timeout=1500)


def run(browser, html, action):
    page = browser.new_page(viewport={"width": 800, "height": 500})
    page.route("**/*", lambda r: r.fulfill(content_type="text/html", body=html)
               if r.request.url == shop.HOME else r.abort())
    page.goto(shop.HOME)
    try:
        action(page)
        page.wait_for_timeout(100)
        seen = page.get_by_role("status").inner_text()
        if seen == EXPECTED:
            return "PASS"
        return f"WRONG RESULT: {seen!r}"
    except Error as error:
        return "ERROR: " + error.message.splitlines()[0].split(": ", 1)[-1][:34]
    finally:
        page.close()


with sync_playwright() as p:
    browser = p.chromium.launch()
    for label, action in [("CSS class", by_css),
                          ("screen position", by_position),
                          ("role and label", by_role)]:
        print(label)
        for version, html in [("old page", shop.ORDER_V1), ("redesign", shop.ORDER_V2)]:
            print(f"   {version:<9} {run(browser, html, action)}")

    page = browser.new_page()
    page.set_content(shop.ORDER_V2)
    try:
        page.get_by_role("button").click(timeout=1500)
    except Error as error:
        print("vague locator:", error.message.split("resolved to ")[1].split(":")[0],
              "-> refused to guess")
    browser.close()

Output:

CSS class
   old page  PASS
   redesign  WRONG RESULT: 'Newsletter joined'
screen position
   old page  PASS
   redesign  WRONG RESULT: ''
role and label
   old page  PASS
   redesign  PASS
vague locator: 2 elements -> refused to guess

Three different outcomes

  • CSS class clicked a button successfully, but it was the newsletter button. No error was raised. Only the outcome check noticed.
  • Screen position clicked empty space after the layout moved. Again, no error.
  • Role and label passed both times and waited for the delayed button to become enabled.

The last line shows a useful refusal: a locator matching two buttons raises an error instead of choosing the first. An agent should receive that error, look again and be more specific, or ask.

Role locators are not magic

If a redesign renames the button or adds a second one with the same name, they fail too. That is the good outcome when they fail loudly. Keep the outcome check.

Where accessible names come from

A role locator matches the name the browser computes for an element. It can come from the button's own text, a connected label, an aria-label, a referenced element or an image's alternative text. This explains common surprises: an icon button with no label has no usable name, and two "Edit" buttons share one name.

# Narrow by the surrounding row instead of taking "the first Edit button"
row = page.get_by_role("row").filter(has_text="A-4279")
row.get_by_role("button", name="Edit", exact=True).click()

# Narrow by the dialog that is open
dialog = page.get_by_role("dialog", name="Change address")
dialog.get_by_label("City").fill("Leeds")

These fragments show the pattern and are not run here. Scope first, then name. If the scoped search still finds two elements, the page or the task is ambiguous, and guessing is the wrong answer.

Give the model a short candidate list

Rather than letting a model write selectors, build a list of visible, enabled elements with a temporary reference, role, name and nearby heading. The model chooses a reference; your code maps it back and acts. Discard references after any navigation or re-render, and reject a reference that was not in the latest list.

e1  textbox  "Quantity"          under "Reorder supplies"   value "1"
e2  button   "Add to basket"     under "Reorder supplies"
e3  button   "Join newsletter"   in banner
Intermediate Dependable actions

Wait for state, not time

Playwright performs actionability checks before many actions, such as that an element is visible, stable, enabled and able to receive the event, and waits until they pass or a timeout expires. Forcing an action skips some of those checks and usually hides a real problem, such as an overlay.

Instead ofWait for
Sleeping five secondsThe confirmation message to appear
Assuming the page loadedThe element you need next
Waiting for all network traffic to stopA specific response or visible state
Retrying the click blindlyChecking whether the first click already took effect

Habits for each action

ActionCheck beforeCheck after
ClickExactly one match; right regionExpected state change
TypeCorrect field, empty or replace intentionallyRead the value back; watch input masks
SelectOption existsSelected value; dependent fields updated
ScrollWhich container scrollsNew content arrived or the end was reached
NavigateAddress is allowedFinal address and page identity after redirects
UploadFile is the approved oneName, size and acceptance message
SubmitValues reviewed; approval if consequentialConfirmation reference saved

Dynamic sites

  • Re-render: element handles go stale. Re-locate at the moment of use.
  • Infinite or virtual lists: only visible rows exist. Search or filter, collect while scrolling and remove duplicates by a key.
  • Pop-ups and cookie banners: handle known ones with explicit rules; choose the privacy-preserving option; report unknown dialogs.
  • Frames and shadow DOM: the target may live inside them. Playwright locators pierce open shadow roots by default, while frames must be addressed.
  • New tabs: follow only expected ones and close the rest.
  • Experiments: two users may see different pages. Do not assume one layout.
  • Locale: dates, decimals and button text change. Fix language and time zone in the browser context where you can.

Typing, files and keyboards

Text entry hides more traps than clicking. A field may reformat what you type, an autocomplete may replace it, a date picker may ignore typed text, and a rich editor may not behave like an ordinary input.

WidgetApproachVerify
AutocompleteType, wait for the list, choose the exact optionThe selected record's identifier, not just its label
Date pickerUse the input if allowed, otherwise navigate by labeled controlsDate in an unambiguous form
Masked number or currencyEnter digits as the field expectsParsed value, including decimal separator
Rich text editorFocus, then type or paste plain textResulting text, no lost line breaks
File uploadSet the file on the input from an approved folderName, size and server acceptance
Custom dropdownOpen it, pick by role and nameDisplayed and submitted value agree

Keyboard shortcuts differ by operating system and application, and pressing Enter can submit a form early. Prefer clicking a named control for anything that commits data. Never type a secret through the model; let a trusted component fill it.

Debugging a failed step

  1. Open the screenshot taken just before the action and ask what a person would have clicked.
  2. Compare the observation given to the model with the real page; trimming may have removed the target.
  3. Count how many elements matched the locator.
  4. Look for overlays, disabled states, frames and scrolling containers.
  5. Replay the step alone, with tracing on, in the same screen size and locale.
  6. Fix the cause, then add the page state to the test range.

Multi-step forms

Step 1fill, validate, record
Step 2fill, validate, record
Review pagecompare with source data
Approvalexact values
Submit oncesave the reference

Keep the intended values in your own structured record. At each step, read back what the page holds and compare. At the end, compare the whole review page with the record. Before retrying a submit that timed out, check the application's list of submissions or search for your reference; a second submission may create a duplicate. If the site offers no way to check, stop and ask a person.

{"task": "supplier-update-118",
 "wanted":  {"contact": "A. Rivera", "city": "Leeds", "start": "2026-12-01"},
 "checked": {"step1": true, "step2": true, "review": false},
 "submitted": null,
 "next": "compare review page"}

This illustrative record lets a run resume after a crash without guessing where it stopped.

Expert Grounding, recovery and measurement

Visual grounding

Grounding means connecting words such as "the blue Save button in the dialog" to a particular place on screen. Approaches include:

ApproachHowWatch for
Coordinates from a vision modelModel returns a point or boxScaling between the image sent and the real screen
Numbered overlayDraw labels on candidate elements; model picks a numberClutter; labels hiding content
Structure plus pictureCandidates from the tree, choice using the screenshotMismatch between tree and what is visible
Text recognitionFind words with OCR, click their boxMisreads; repeated words
Template matchingFind a known icon imageThemes, scaling, new icons

When you click by coordinates: convert them for device scale and resizing, take the screenshot immediately before the click, confirm that the element under the point is the one intended where the platform allows it, and confirm the result with a new observation.

Scaling arithmetic

A 2560 pixel wide screen is shrunk to 1280 pixels before the model sees it. A returned x of 640 means screen x 1280. Forgetting the factor of 2 clicks the wrong half of the screen.

Recover with a ladder

  1. Observe again; the page may have been loading.
  2. Dismiss a known overlay.
  3. Try a different identification method, still unambiguous.
  4. Return to the last checkpoint and repeat a safe step.
  5. Stop and hand over with the screenshot, the goal and what was already done.

Only repeat steps that are safe to repeat. See Reliable Tool Execution and Error Recovery and Workflow Versioning, Testing and Resilience.

What counts as proof

EvidenceStrength
The agent says it succeededNone
No error was raisedVery weak
A success message appearedUseful; may be premature or generic
The saved record shows the intended values after reloadStrong
The system of record confirms by API or exportStrongest

Write the check before the automation. Compare values exactly after normalizing only what you understand, such as trimming spaces, and include a negative check: nothing else changed, no second record was created.

Combine learned and fixed paths

Once a model has found a route through a stable page, you can record the locators and replay them as code, calling the model again only when a check fails. This lowers cost and variance. Record by role and label, review the recorded steps as you would review code, and expire them when the application is released.

If you own the application

You can make agents and people succeed together: use real buttons, links and labels; give status messages a status role; keep names stable; avoid layout jumps; offer test identifiers; show a reference after every submission; and, better still, publish an API or an MCP server so the screen is no longer needed.

Measure reliability

MeasureMeaning
Verified success rateRuns whose end state is correct
ConsistencyTasks that pass every one of N repeats
Silent error rateRuns reported successful but wrong
Wrong-element rateActions on an unintended target
Recovery rateFailures resolved without a person
Steps, time and cost per successEfficiency

Drive the silent error rate toward zero first. A loud failure costs a retry; a silent one costs trust. A simple calculation shows why repeats matter: if each of 20 independent steps succeeds 99% of the time, the whole task succeeds about 82% of the time (0.99 to the power 20). Real steps are not independent, so measure whole tasks.

Common mistakes

MistakeBetter practice
Picking the first of several matchesRequire one match or narrow it
Fixed sleepsWait for a named state
Forcing clicks to silence errorsFind what is blocking the element
Checking only that no error occurredRead the application's state
Replaying a submit after a timeoutCheck whether it already happened
Testing one screen size and languageTest those your users and agents use

Checklist

  • Elements identified by role, name, label or maintained test id
  • Ambiguous matches cause an error
  • Waits target visible state
  • Every task step has a verification
  • Submissions are checked before any retry
  • Recovery ends in a clear handover
  • Silent errors are measured on repeated runs

Frequently asked questions

Are test identifiers better than roles?

For applications you control, they are very stable. Roles also check what a user can perceive. Many teams use roles first and identifiers where names are unstable.

What if a site has no accessible names?

Combine structure with screenshots, anchor to nearby text, add stronger verification and expect more maintenance.

Should the agent retry a failed click?

Only after checking that it had no effect and understanding why it failed. Limit attempts.

Is a higher timeout a fix?

It helps with slow pages but not with a wrong locator. Look at the error and the screenshot before raising it.

References and further reading

Next steps