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.
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.
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.
Ways to identify an element
| Method | Example idea | Survives a redesign? |
|---|---|---|
| Role and accessible name | button "Add to basket" | Usually, while the meaning stays |
| Label or placeholder | field labeled "Quantity" | Usually |
| Test identifier | data-testid="add" | Yes, if your team maintains it |
| Visible text | "Add to basket" | Breaks with wording or language changes |
| CSS class or generated id | button.primary | Often not |
| XPath by position | third div, second button | Rarely |
| Screen coordinates | click 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.
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
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 of | Wait for |
|---|---|
| Sleeping five seconds | The confirmation message to appear |
| Assuming the page loaded | The element you need next |
| Waiting for all network traffic to stop | A specific response or visible state |
| Retrying the click blindly | Checking whether the first click already took effect |
Habits for each action
| Action | Check before | Check after |
|---|---|---|
| Click | Exactly one match; right region | Expected state change |
| Type | Correct field, empty or replace intentionally | Read the value back; watch input masks |
| Select | Option exists | Selected value; dependent fields updated |
| Scroll | Which container scrolls | New content arrived or the end was reached |
| Navigate | Address is allowed | Final address and page identity after redirects |
| Upload | File is the approved one | Name, size and acceptance message |
| Submit | Values reviewed; approval if consequential | Confirmation 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.
| Widget | Approach | Verify |
|---|---|---|
| Autocomplete | Type, wait for the list, choose the exact option | The selected record's identifier, not just its label |
| Date picker | Use the input if allowed, otherwise navigate by labeled controls | Date in an unambiguous form |
| Masked number or currency | Enter digits as the field expects | Parsed value, including decimal separator |
| Rich text editor | Focus, then type or paste plain text | Resulting text, no lost line breaks |
| File upload | Set the file on the input from an approved folder | Name, size and server acceptance |
| Custom dropdown | Open it, pick by role and name | Displayed 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
- Open the screenshot taken just before the action and ask what a person would have clicked.
- Compare the observation given to the model with the real page; trimming may have removed the target.
- Count how many elements matched the locator.
- Look for overlays, disabled states, frames and scrolling containers.
- Replay the step alone, with tracing on, in the same screen size and locale.
- Fix the cause, then add the page state to the test range.
Multi-step forms
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.
Visual grounding
Grounding means connecting words such as "the blue Save button in the dialog" to a particular place on screen. Approaches include:
| Approach | How | Watch for |
|---|---|---|
| Coordinates from a vision model | Model returns a point or box | Scaling between the image sent and the real screen |
| Numbered overlay | Draw labels on candidate elements; model picks a number | Clutter; labels hiding content |
| Structure plus picture | Candidates from the tree, choice using the screenshot | Mismatch between tree and what is visible |
| Text recognition | Find words with OCR, click their box | Misreads; repeated words |
| Template matching | Find a known icon image | Themes, 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.
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
- Observe again; the page may have been loading.
- Dismiss a known overlay.
- Try a different identification method, still unambiguous.
- Return to the last checkpoint and repeat a safe step.
- 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
| Evidence | Strength |
|---|---|
| The agent says it succeeded | None |
| No error was raised | Very weak |
| A success message appeared | Useful; may be premature or generic |
| The saved record shows the intended values after reload | Strong |
| The system of record confirms by API or export | Strongest |
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
| Measure | Meaning |
|---|---|
| Verified success rate | Runs whose end state is correct |
| Consistency | Tasks that pass every one of N repeats |
| Silent error rate | Runs reported successful but wrong |
| Wrong-element rate | Actions on an unintended target |
| Recovery rate | Failures resolved without a person |
| Steps, time and cost per success | Efficiency |
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
| Mistake | Better practice |
|---|---|
| Picking the first of several matches | Require one match or narrow it |
| Fixed sleeps | Wait for a named state |
| Forcing clicks to silence errors | Find what is blocking the element |
| Checking only that no error occurred | Read the application's state |
| Replaying a submit after a timeout | Check whether it already happened |
| Testing one screen size and language | Test 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
- Playwright: locators
- Playwright: auto-waiting and actionability
- W3C: accessible name computation
- Selenium: test practices
Next steps
Browser Agent Safety, Testing and Recovery
Add limits and a test suite.
Lab: Browser Agent and Coding Agent
Practice on a local site.
Tool Testing and Observability
Trace what actions did.