How to Write Stable Selenium Locators That Don't Break
The 7 rules for writing Selenium locators that survive UI changes. Real examples, anti-patterns to avoid, and a free selector generator that emits Page Object classes.
2026-07-17 · By Avinash Kamble, reviewed by Priyanka G.
Selenium suites don't fail because Selenium is broken — they fail because locators broke overnight when someone renamed a class or reordered a div. Here are the seven rules senior SDETs enforce in code review.
1. Prefer id, then data-* attributes
An id is the fastest and most stable locator. If none exists, ask developers to add a data-testid. Both survive Tailwind refactors, i18n renames, and component library upgrades.
driver.findElement(By.id("submit-btn")).click();
driver.findElement(By.cssSelector("[data-testid='pricing-pro']")).click();2. Never write absolute XPath
Any XPath that starts with /html/ is a bug waiting to ship. Refactor to relative XPath or CSS the moment you see one in a PR.
// BAD
driver.findElement(By.xpath("/html/body/div[2]/div[1]/form/button"));
// GOOD
driver.findElement(By.xpath("//form[@id='login']//button[normalize-space()='Sign in']"));3. Scope locators inside containers
When a page has repeated patterns (table rows, cards, list items), find the parent first and search within it. This avoids brittle nth-child selectors and gives clearer failure messages.
WebElement row = driver.findElement(By.xpath("//tr[td[normalize-space()='Acme Corp']]"));
row.findElement(By.cssSelector("button.delete")).click();4. Use Selenium 4 relative locators for edge cases
Selenium 4 shipped above(), below(), toLeftOf(), toRightOf(), and near(). Great for visually-defined elements without stable attributes.
WebElement password = driver.findElement(with(By.tagName("input")).below(emailField));5. Wrap everything in a Page Object
Never let a raw By.xpath(...) live inside a test method. When the DOM changes you want to update one file, not fifty tests. The free selector generator emits a ready-to-commit Page Object in Java, TypeScript, Python, or C#.
6. Add explicit waits, delete Thread.sleep
new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.id("submit-btn")));7. Review locators like you review production code
Add a "locator quality" checklist to your PR template: prefer id/data-testid, no absolute XPath, no Thread.sleep, no raw selectors inside tests, POM wrapping. Enforcing this for a single quarter typically cuts flake rate by 60%+.
Frequently asked questions
1.What is the most reliable Selenium locator?
2.Should I use CSS or XPath in Selenium?
3.How do I handle dynamic ids?
4.How do I test my locators before running the suite?
Practice these questions
Work through 300+ Selenium questions with Java code snippets, Selenium 4, Grid, framework patterns and CI/CD scenarios.
Was this article helpful?
More from Selenium WebDriver Basics
Locators, waits, WebDriver setup — the foundation.
- Automation TestingThe Complete Selenium WebDriver Guide (2026): From Zero to Production-Ready Automation
- Automation TestingSelenium Python Automation Interview: 25 Questions (2026)
Keep building your QA edge
Pillar guides- Playwright PillarPlaywright automation guide300 Playwright Q&A, framework design, and migration guides.
- XPath & CSS Selector Generatorgenerate robust Playwright and Selenium locatorsInteractive locator generator for Playwright, Selenium and Cypress — with Page Object export.
- AI Mock Interviewpractice these questions with our AI mock interviewLive AI-powered mock interviews with rubric feedback.
Practice these questions live
Rehearse with an AI QA interviewer that scores your answers in real time.
Continue reading

Playwright Locator Best Practices (2026) — The Only Guide You Need
11 min read
How to Migrate a Postman Collection to Playwright API Tests (2026 Guide)
12 min read
Why Every QA Engineer Must Master CI/CD Pipelines in 2026 (Or Risk Obsolescence)
12 min readJoin the QA Community
Connect with fellow testers, share job leads, and get career advice.
Stop Reinventing the Wheel. Upgrade Your QA Arsenal.
Take your testing skills from beginner to Lead Engineer. Supercharge your daily workflow with our premium digital resources.
- Ready-to-use testing strategy templates
- Advanced API & UI automation guides
- ⏱️ Save 10+ hours a week on test planning