ThisCalculator

Everyday

Selenium Locators: Cheat Sheet, Examples & Selection Tips

Updated · Standard formula, shown below

Selenium Locators: Cheat Sheet, Examples & Selection Tips

This guide explains how to choose and use Selenium locators—the strategies that find elements on a web page—with a cheat sheet of syntax, concrete examples, and practical selection tips. You’ll learn the strengths and weaknesses of each locator type, common pitfalls, and how to pick the most reliable one for your test.

What Are Selenium Locators?

Selenium WebDriver uses locators to identify HTML elements so your test can interact with them—clicking, typing, reading text, or verifying visibility. A locator is a query that matches one or more elements in the Document Object Model (DOM). The choice of locator directly affects test stability: a poorly chosen locator breaks when the UI changes, while a robust one survives minor layout or text edits.

There are eight built-in locator strategies in Selenium: ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath. Each has its own syntax and use case. Modern Selenium also supports relative locators (above, below, near, toLeftOf, toRightOf) introduced in version 4, which locate elements based on their position relative to other elements.

Cheat Sheet: Syntax and Examples

Here is a quick reference for each locator strategy, with a real-world example and the corresponding Selenium code (Java syntax shown, but the same logic applies to Python, C#, etc.).

  • ID – By.id("username") – matches the id attribute. Example: <input id="username">. Fastest and most reliable when present.
  • Name – By.name("email") – matches the name attribute. Example: <input name="email">. Good for form fields.
  • Class Name – By.className("btn-primary") – matches the class attribute. Example: <button class="btn btn-primary">. Note that it matches the entire class string, not individual classes.
  • Tag Name – By.tagName("div") – matches the HTML tag. Example: <div></div>. Useful for finding all elements of a type, but rarely unique.
  • Link Text – By.linkText("Sign In") – matches the exact visible text of an <a> tag. Example: <a href="/login">Sign In</a>.
  • Partial Link Text – By.partialLinkText("Sign") – matches a substring of the link text. Use when the full text is dynamic or long.
  • CSS Selector – By.cssSelector("#login-form input[type='email']") – uses CSS syntax to match elements. Example: <form id="login-form"><input type="email"></form>. Very flexible and faster than XPath in most browsers.
  • XPath – By.xpath("//div[@class='product']//span[text()='Add to Cart']") – uses XML path syntax. Can traverse the DOM in ways CSS cannot, e.g., finding a parent element or using text content.

How to Choose the Right Locator

Selection is a trade-off between speed, readability, and resilience. The general priority order recommended by most test automation engineers is:

  1. ID – if it exists and is unique, use it. It’s the fastest and most stable.
  2. Name – good for form inputs, but ensure uniqueness.
  3. CSS Selector – when no ID/name, CSS is often the next best because it’s concise and performs well.
  4. XPath – use when you need to navigate the DOM hierarchically or match by text; otherwise avoid due to slower performance and fragility.
  5. Link Text / Partial Link Text – only for links; prefer exact text when possible.
  6. Class Name / Tag Name – rarely unique; use only when combined with other attributes or when you need a list of elements.

When a locator is not unique, you can refine it. For CSS, use input[type='submit'] or .btn.primary. For XPath, use //button[contains(@class,'submit')] or index //div[2]/span (but indexing is fragile). Always prefer attributes that are stable—like data-testid if your team adds them—over text that might change.

Common Mistakes and How to Avoid Them

Even experienced testers fall into these traps:

  • Using absolute XPath like /html/body/div[2]/form/input. Any minor DOM change breaks it. Use relative XPath starting with //.
  • Matching multiple elements – By.className("btn") might return several buttons. Use findElements and index, or refine the locator.
  • Depending on dynamic classes – CSS classes like active or error often change. Look for stable IDs or custom attributes.
  • Ignoring whitespace – linkText("Sign In") fails if there’s a newline in the HTML. Use normalize-space() in XPath or trim in your code.
  • Using XPath for everything – it’s slower and harder to read. CSS is usually sufficient and more maintainable.

CSS Selector vs. XPath: Which Is Better?

This is a frequent debate. CSS selectors are generally faster in modern browsers because they are optimized for CSS engine. They are also more readable. XPath is more powerful: it can select elements based on text content (//button[text()='Submit']), traverse to parent elements (..), and use functions like contains(), starts-with(), and not(). CSS cannot do any of these directly.

Practical advice: Use CSS for attribute-based selection (ID, class, tag, attribute values). Use XPath when you need to find an element by its visible text, or when the DOM structure requires moving up or sideways. For example, to find a row that contains a specific cell value, XPath is the only built-in option.

Relative Locators in Selenium 4

Selenium 4 introduced relative locators that let you find elements near other elements. For instance, driver.findElement(withTagName("input").below(By.id("username"))) finds an input below the username field. This is useful for form validation messages or adjacent buttons. However, they are not a replacement for traditional locators—they are best for specific spatial relationships and can be slower due to extra computation.

Tips for Writing Robust Locators

  • Prefer unique attributes – ask developers to add data-testid attributes for testing. This decouples tests from UI styling.
  • Avoid text-based locators unless the text is part of the requirement (e.g., verifying a link label). Text changes often.
  • Use findElements to verify count – if you expect one element, check that size() == 1 to catch duplicate matches early.
  • Keep locators short – long XPath chains are brittle. Break them into variables or use helper methods.
  • Test locators in the browser console – use document.querySelector() for CSS or $x() in Chrome DevTools to verify they match the intended element before writing code.
  • Use explicit waits – a locator may be correct but the element is not yet present. Always pair with WebDriverWait.

Frequently Asked Questions

Q: What is the fastest locator in Selenium?
ID is the fastest because browsers optimize lookup by ID. Next are CSS selectors, then XPath. However, the difference is negligible for small pages; reliability matters more.

Q: Why is my XPath not finding the element even though it exists?
Common reasons: the element is inside an iframe (switch to it first), the page has not fully loaded (use waits), or the XPath is case-sensitive. Also check for leading // vs /.

Q: Can I use multiple classes in a CSS selector?
Yes, use .class1.class2 without spaces. For example, .btn.primary matches elements with both classes.

Q: How do I find an element by its text content?
Use XPath: //button[text()='Submit'] or //div[contains(text(),'Error')]. CSS cannot select by text.

Q: What is the difference between findElement and findElements?
findElement returns the first matching element or throws NoSuchElementException if none. findElements returns a list (possibly empty) of all matches. Use findElements to check existence or handle multiple elements.

Q: Are locators case-sensitive?
Yes, attribute values and tag names are case-sensitive in HTML. For example, id="Login" is different from id="login". XPath is also case-sensitive; use @id='Login' exactly.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.