Skip to main content

Selectors the Agent Chooses

Why This Matters

Most broken UI tests are broken by a selector. A developer renames a class, wraps a button in a new div, or adds a second “Save” button, and a test that checked a perfectly working feature turns red. The second most common problem is the opposite: a selector that matches the wrong element and lets a test pass that should fail.

An AI that guesses selectors makes both problems worse: it invents class names that look plausible, or writes //div[3]/button because that is what it saw. Selenium AI Agent takes selectors out of the AI’s imagination. It computes them from the live page, checks them before a test is saved, lets a person teach better ones, and under the strict profile only allows selectors a person has seen.

What you will learn

  • How the agent computes a selector for every element, and in which order it prefers them
  • How selectors are checked against the live page before a test is saved
  • browser_generate_locator: a locator from a plain description
  • teach_selector: when you know a better selector than the agent
  • Locked locators under strict (guardrail 3)
  • Shadow DOM, briefly

Every element comes with a selector

You saw it in lesson 3: capture_page returns every element with a ref and a ready-made selector:

- button "shopping_cart0 items$0.00" [ref=e13, css=button[data-testid="cart-button"]]
- textbox "Search for items" [ref=e16, css=input[data-testid="search-input"]]
- heading "E-commerce Testing Practice" [level=1] [ref=e12, xpath=//h1[normalize-space()='E-commerce Testing Practice']]
- button "Previous page" [ref=e47, css=button[aria-label="Previous page"]]

The selector is computed by an engine that tries strategies in a fixed order and takes the first one that matches exactly one visible element:

OrderStrategyExample
0Taught by youwhatever you taught with teach_selector
1Id#login-form
2Test id[data-testid="cart-button"]
3Role and accessible namebutton[aria-label="Previous page"]
4Label//label[normalize-space()='Email']//input
5Placeholderinput[placeholder="Search..."]
6Visible text//h1[normalize-space()='E-commerce Testing Practice']
7Other attributesimg[alt="Bluetooth Headphones"], a[hreflang="nl"]
9–13ARIA role, state, table cell, combined attributes, meaningful classdialog[open], button.primary-action
14–16Position, loose text, index#sidebar > ul > li:nth-of-type(3), (//button[normalize-space()='Save'])[2]

Three details make the difference with a naive approach:

  • Visible elements only. A hidden duplicate (a mobile menu, an old modal) does not make a selector “not unique”. Otherwise the engine would fall back to a fragile position.
  • Scoping. When a[href="/"] matches the logo and the Home link, the engine scopes it to the nearest landmark: nav[aria-label="Main navigation"] a[href="/"].
  • No generated class names. CSS-in-JS hashes (css-1x2y3z), Tailwind utilities (px-4 py-2) and framework classes are skipped: they change with every build.

Positions (14–16) are a last resort, and when the engine has to use one, the generator prefers a text-based XPath over it.

Checked before saving

generator_write_test extracts the selectors from the test code and tries each one in the browser before it saves the file. A selector that matches nothing is reported:

Selector validation: 4/5 valid. Invalid: "#placeOrderBtn"

The file is written anyway (the page may simply be in a different state than the test expects at that point), but the agent sees the report and should fix the selector. healer_fix_test does the same for every fix. This is guardrail 3 from lesson 4.

A locator from a description

Sometimes you know the element but not a good selector. browser_generate_locator takes a plain description and returns locators for every language:

Give me a locator for the search box.

{
  "element": { "tag": "input", "testId": "search-input" },
  "locators": {
    "recommended": "[data-testid=\"search-input\"]",
    "python": "(By.CSS_SELECTOR, '[data-testid=\"search-input\"]')",
    "java": "By.cssSelector(\"[data-testid=\\\"search-input\\\"]\")",
    "csharp": "By.CssSelector(\"[data-testid=\\\"search-input\\\"]\")",
    "robot": "css:[data-testid=\"search-input\"]"
  }
}

It matches your words against each element’s own text, label, placeholder and test id first, then against the content around it, and it knows kind words: “box”, “button”, “dropdown”, “link”, “checkbox”. It also returns alternatives with their scores.

Read the alternatives. Where a page has many look-alike elements, such as an “Add to Cart” button in every product card, the description must say which one: “the Add to Cart button of the Mechanical Keyboard”. If several elements still fit equally well, the result says ambiguous: true and asks for a more precise description; check the alternatives before you use the locator. While writing this course we found that 3.9.0 silently picked the first product’s button in exactly this case, because it read only the price row next to the button instead of the whole card; 3.9.1 reads the whole card. That is the general lesson too: a tool that answers confidently can still answer wrongly, so check the result in the page.

Teach a better selector

You know your application better than the engine. When it picks something you don’t trust, teach it:

teach_selector({
  "description": "the NL language link",
  "css": "a[href='/nl/']"
})

The selector is checked in the browser first: it must match exactly one visible element. It is saved in selector-hints.json in your project and becomes strategy 0: from then on, every snapshot on that site uses it. The scope is chosen for you: elements in the header, navigation or footer apply site-wide (*), content elements to the current path pattern (/blog/*). You can pass scope to override.

{
  "example.com": {
    "*": [
      { "css": "a[href='/nl/']", "tag": "a", "text": "NL" }
    ]
  }
}

Commit selector-hints.json with your tests: it is part of how your suite finds elements.

Locked locators under strict

Under explore and guided, a test may use any selector the agent found or computed. Under strict it may only use locked locators: the ones a person has seen. There are three sources:

  1. the Elements table of the approved plan the test implements (lesson 8),

  2. locators.json in the project, a list you maintain:

    { "locators": [
      { "name": "Search results heading", "locator": "//h2[contains(., 'Search Results')]" },
      { "name": "Product detail pop-up", "locator": "[data-testid=\"product-detail-modal\"]" }
    ] }
    
  3. selectors taught with teach_selector.

A placeholder in the plan, such as [data-testid="add-to-cart-<id>"], allows that locator for every product id, but nothing wider.

Every locator in the code is compared with that set, in any spelling: #q, By.ID "q" and id=q are the same locator. A test that uses another one is refused. For test 1.1 of the shop plan, whose heading check uses an XPath that is not in the plan’s Elements, the refusal reads:

Test not written: the profile uses locked locators, and these are not in the locked set (the plan's Elements (9)):
  line 6: xpath "//h2[contains(., 'Search Results')]"
Use a locator from the plan's Elements or locators.json. For a new element: ask the user to add a test id or
approve the locator, then teach it with teach_selector (or add it to locators.json) and try again.

That is the point: under strict, a test never passes because the model guessed a selector. The healer is held to the same set (lesson 16), and the CI gate checks it again (lesson 18).

There are two good answers to this refusal. Ask a developer to add a test id to the heading (best: the test id then goes into the plan), or approve the XPath by adding it to locators.json.

Shadow DOM, briefly

Web components hide their inner elements in a shadow root, where By.CSS_SELECTOR and XPath can’t reach. The agent’s discovery goes into open shadow roots and writes such selectors as host >>> inner, like Playwright. browser_generate_locator returns the Selenium code for them (.shadow_root.find_element(...) in Python, getShadowRoot() in Java and JavaScript). For Salesforce Lightning, whose shadow DOM is a JavaScript imitation that WebDriver can’t enter at all, it returns a small helper file instead. You won’t need this for the shop; you will on many enterprise applications.

Exercise

On the shop page:

  1. Ask for a locator for “the Add to Cart button of the Desk Lamp”. Is the recommended locator right? Check it in the page: which product’s card is it in? What do the alternatives say?
  2. Ask for a locator for “Add to Cart button” without naming a product. What does the result tell you?
  3. Teach the selector [data-testid="results-count"] as “the number of search results”. Then run capture_page again: which selector does the results count get now?
Show suggested answer
  1. The Desk Lamp is product 9, so the right locator is [data-testid="add-to-cart-9"], inside the Desk Lamp’s card. The alternatives are the other buttons, with lower scores. (Had they had the same score, the description would not have singled out one element.)
  2. Several buttons fit equally well, so the result says ambiguous and asks for a more precise description. Never use a locator from an ambiguous description.
  3. The taught selector is strategy 0, so the results count now shows css=[data-testid="results-count"] (it was already a test id here, so nothing visible changes; teaching matters when the engine chose something weaker). Check selector-hints.json in your project: the hint is there, under the shop’s host and the /shopping path.

Exam-style questions

Quiz

1. Two elements match [data-testid="close"], but one of them is hidden. What does the selector engine do?

  • A. Falls back to a positional selector
  • B. Uses [data-testid="close"]: only visible elements count for uniqueness
  • C. Refuses to give the element a selector
  • D. Uses the hidden element
Show answer
B.
Quiz

2. Under the strict profile, which locators may a generated test use?

  • A. Any locator that works on the page
  • B. Only locators from the approved plan’s Elements, locators.json and taught selectors
  • C. Only test ids
  • D. Only XPath
Show answer
B.
Quiz

3. generator_write_test finds that one selector in the test matches nothing on the page. What happens?

  • A. The test is refused
  • B. The test is written and the agent gets a validation report naming the selector
  • C. The selector is replaced automatically
  • D. The browser is restarted
Show answer
B. The check is a report, not a refusal: the page may be in a different state at that moment. Under strict, a selector that is not in the locked set is refused.