Locators: ID, Name, CSS, XPath, and Best Practices
Learn how Selenium finds elements and why locator strategy is one of the most important factors in stable test automation.
Inside this chapter
- Why Locators Are So Important
- Common Locator Strategies
- Basic Locator Example
- CSS vs XPath
- Best Practices for Stable Locators
- Real-Time Example
Series navigation
Study the chapters in order for the clearest path from Selenium setup and locators to framework design, CI integration, flaky-test control, and advanced automation engineering practice. Use the navigation at the bottom to move smoothly through the full tutorial series.
Why Locators Are So Important
If Selenium cannot identify the correct element reliably, the test becomes fragile. Strong locator strategy is the foundation of maintainable browser automation. Many flaky suites fail not because Selenium is weak, but because element identification is poorly designed.
Common Locator Strategies
- ID
- Name
- Class name
- Tag name
- Link text and partial link text
- CSS selector
- XPath
Basic Locator Example
driver.findElement(By.id("email")).sendKeys("student@example.com");
driver.findElement(By.cssSelector("button[type='submit']")).click(); CSS vs XPath
CSS selectors are often simpler and faster to read. XPath can be more expressive for complex tree relationships. Strong engineers know both, but they prefer the simplest reliable locator rather than the most clever one.
Best Practices for Stable Locators
- Prefer stable IDs or test-specific attributes where possible
- Avoid fragile absolute XPath
- Avoid locators based on changing style classes only
- Collaborate with developers to add automation-friendly attributes
- Keep locators readable and intention-revealing
Real-Time Example
An e-commerce search test may fail every sprint if it locates the search input through a deeply nested absolute XPath tied to layout changes. The same test may remain stable for months if it uses a dedicated test id or semantic selector.