Selenium Locators: ID, CSS, XPath and More
A locator tells Selenium which element to use. Bad locators are the number one reason automated tests break. Good ones survive design changes.
The locator strategies
| Strategy | Example | Notes |
|---|---|---|
| ID | By.id("email") | Fast and stable if the ID is fixed. |
| Name | By.name("email") | Good for form fields. |
| CSS selector | By.cssSelector("[data-testid='login-submit']") | Flexible and fast. Use it most. |
| XPath | By.xpath("//button[text()='Log in']") | Can find by text and walk up the page. Easy to make fragile. |
| Link text | By.linkText("Create an account") | Only for links. Breaks when the text changes. |
| Class name | By.className("btn") | Classes are for styling and change often. Avoid. |
| Tag name | By.tagName("h1") | Only when there is exactly one. |
Which one to pick
- A test ID such as
data-testid, added for testing. Ask developers to add them. The practice pages on this site have them. - A unique, fixed ID or name.
- A short CSS selector based on attributes, not on layout.
- XPath with text, only when nothing else works.
CSS selectors you will use every day
#email id="email"
[name='email'] attribute equals
[data-testid='login-submit'] test id
button[type='submit'] tag plus attribute
form#login input[type='email'] element inside another
[id^='user-'] id starts with
[id*='error'] id contains
XPath you should know
//button[text()='Log in'] exact text
//button[contains(text(),'Log')] part of the text
//label[text()='Email']/following-sibling::input
//td[text()='Demo Tester']/parent::tr go up to the row
Locators to avoid
- Absolute XPath like
/html/body/div[2]/div/form/input[1]. One new div and it breaks. - Generated classes like
.css-1x2y3zor long styling classes. - Indexes like
(//input)[3], unless the order really is the point of the test.
Check a locator before you use it
Open Chrome DevTools (F12), press Ctrl+F (Cmd+F on Mac) in the Elements tab and paste your CSS or XPath. It shows how many elements match. You want exactly 1 of 1.
findElement vs findElements
findElementreturns one element and throwsNoSuchElementExceptionif there is none.findElementsreturns a list, which is empty if there are none. Use it to check that something is not on the page.
Practice: open the automation playground and write one CSS and one XPath locator for every element on it.
All 9 lessons in Selenium with Java
- What Is Selenium WebDriver?
- Set Up Java, Maven and Selenium
- Write Your First Selenium Test
- Selenium Locators: ID, CSS, XPath and More
- Clicks, Typing, Dropdowns, Alerts, Frames and Windows
- Waits in Selenium: Implicit, Explicit and Fluent
- TestNG for Selenium: Annotations, Assertions and Data
- Page Object Model in Selenium Java
- Selenium Framework Structure, Reports and CI