QuickDevGuide

Home › Selenium Automation (Java)

Locator Strategies — Selenium Automation (Java)

Stable locators are the single biggest factor in a maintainable suite. Strategy Example Notes By.id By.id("email") fast and stable if IDs aren't generated test attribute By.cssSelector("[data-testid='checkout']") best — agree on it with developers By.name By.name("q") good for forms By.cssSelector "form#login button[type=submit]" flexible, fast By.xpath "//button[normalize-space()='Pay now']" only when you need text or axes By.linkText By.linkText("Sign out") links only, breaks on text changes By.className / tagName rarely unique Relative locators (Selenium 4) with(By.tagName("input")).below(labelEl) layout-based fallback Avoid Absolute XPath (/html/body/div[3]/div[2]/...) — breaks with any layout change. Auto-generated classes/IDs (css-1x2y3z, ember123). Index-based selectors unless…

Key Takeaways