Q6 of 37 · Selenium

List the locator strategies in Selenium and rank them by reliability.

SeleniumJuniorseleniumlocatorsfundamentalsstability

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=...] via By.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(...) and By.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.

// WHAT INTERVIEWERS LOOK FOR

Recognising that ranking is about stability, not Selenium feature parity. Naming data-test attributes as the gold standard. Calling out positional xpath as the failure mode.

// COMMON PITFALL

Treating xpath as 'most powerful so most reliable.' XPath is the most powerful, but it's also the easiest to write fragile — power and stability are different axes.