Which locator strategy is generally the most robust in Selenium?
Options
- A stable attribute such as
idordata-testid(Correct option) - Absolute XPath like
/html/body/div[3]/div[2]/button - The position number of the element
- The text color of the element
Answer
A dedicated, stable attribute such as id or data-testid; avoid long absolute XPath tied to page layout
Why
Locators find elements: By.id, By.name, By.cssSelector, By.xpath, By.linkText.
A locator breaks when the page changes. Absolute XPath breaks with any layout change. Stable hooks are best: id or a test attribute like data-testid="submit", agreed with the front-end team.
CSS selectors are usually faster and more readable than XPath; use XPath when you need text or parent navigation.
Remember
Prefer id / data-testid. Avoid long absolute XPath.