Selenium with Java · Locators and Actions

Selenium Locators: ID, CSS, XPath and More

Lesson 4 of 9 · 11 min read

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

StrategyExampleNotes
IDBy.id("email")Fast and stable if the ID is fixed.
NameBy.name("email")Good for form fields.
CSS selectorBy.cssSelector("[data-testid='login-submit']")Flexible and fast. Use it most.
XPathBy.xpath("//button[text()='Log in']")Can find by text and walk up the page. Easy to make fragile.
Link textBy.linkText("Create an account")Only for links. Breaks when the text changes.
Class nameBy.className("btn")Classes are for styling and change often. Avoid.
Tag nameBy.tagName("h1")Only when there is exactly one.

Which one to pick

  1. A test ID such as data-testid, added for testing. Ask developers to add them. The practice pages on this site have them.
  2. A unique, fixed ID or name.
  3. A short CSS selector based on attributes, not on layout.
  4. 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-1x2y3z or 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

  • findElement returns one element and throws NoSuchElementException if there is none.
  • findElements returns 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
  1. What Is Selenium WebDriver?
  2. Set Up Java, Maven and Selenium
  3. Write Your First Selenium Test
  4. Selenium Locators: ID, CSS, XPath and More
  5. Clicks, Typing, Dropdowns, Alerts, Frames and Windows
  6. Waits in Selenium: Implicit, Explicit and Fluent
  7. TestNG for Selenium: Annotations, Assertions and Data
  8. Page Object Model in Selenium Java
  9. Selenium Framework Structure, Reports and CI