Q6 of 37 · Selenium
List the locator strategies in Selenium and rank them by reliability.
Short answer
Short answer: The strategies are id, name, css, xpath, class name, tag name, link text, partial link text. Practical ranking: data-test attributes via CSS > id > name > scoped CSS > xpath > class/tag/link text. Stable hooks beat clever selectors.
Detail
Selenium ships eight locator strategies. They aren't equally reliable, and the right ranking has more to do with selector stability than with any property of Selenium itself.
Tier 1 — purpose-built test hooks:
[data-test="submit"],[data-cy=...],[data-testid=...]viaBy.cssSelector. These attributes exist for tests, so a UI refactor that doesn't change the data-attribute leaves your tests intact. This is the gold standard.By.id(...)— second-best when ids are stable, app-controlled, and unique.
Tier 2 — semantic, fairly stable:
By.name(...)for form fields with stable name attributes.- Scoped CSS based on roles, labels, or stable structural relationships (
[role=dialog] [data-test=ok]).
Tier 3 — usable but fragile:
By.xpath(...)— powerful for text matching and traversals CSS can't do, but easy to write fragile (//div/div[3]/span). Stick to attribute or text-based xpath, never positional.By.linkText(...)andBy.partialLinkText(...)— fine for stable copy, but copy changes break tests.
Tier 4 — last resort:
By.className(...)— class names change with refactors and CSS-in-JS often produces hashed class names.By.tagName(...)— almost always too broad to be useful.
The senior point: the locator strategy is downstream of whether the app team adds test hooks. The single highest-leverage move is to convince devs to add data-test attributes; everything else is working around their absence.