October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

Selenium WebDriver Locators: Strategies, Examples, and How to Choose

A practical guide to Selenium’s eight locator strategies, with Java examples, advice for choosing stable selectors, and guidance on multiple matches.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Selenium WebDriver locators identify elements in a page’s DOM so your test can read or interact with them. Selenium documents eight traditional strategies: ID, CSS selector, name, class name, link text, partial link text, tag name, and XPath. Start with a unique, stable ID when one is available; otherwise, Selenium recommends a well-written CSS selector. Use plural finding methods when several matches are expected, and make singular lookups specific enough to target the intended element.

What a Selenium locator does

A locator describes how Selenium should find one or more elements in the current page. The strategy is chosen in your language binding, and the page’s DOM determines what matches. A locator can match no elements, one element, or several; it does not guarantee uniqueness by itself.

As an Amazon Associate I earn from qualifying purchases.

The examples below use Java and Selenium’s By API. Selenium’s official locator reference includes examples for multiple language bindings, so check the matching binding documentation if you use another language: Selenium WebDriver: Locating elements.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The eight traditional locator strategies

Strategy What it matches Java example When it fits
ID An element with the specified id attribute. By.id("fname") Prefer a unique, stable ID when the application provides one.
CSS selector Elements matching a CSS selector. By.cssSelector("#fname") Use a well-written selector when there is no unique ID, or when a useful attribute or relationship can be expressed clearly.
Name An element with the specified name attribute. By.name("newsletter") Useful for forms with meaningful, stable field names.
Class name Elements whose class attribute contains the specified class. By.className("information") Useful when the class is meaningful; a shared class may match multiple elements. A compound class name is not permitted in this strategy.
Link text An anchor whose visible text exactly matches. By.linkText("Selenium Official Page") Use for a link with stable, distinctive visible text; it applies only to links.
Partial link text An anchor whose visible text contains the specified text. By.partialLinkText("Official Page") Use when matching a distinctive portion of link text is intentional. It applies only to links, and if multiple links match, the documented behavior selects the first.
Tag name Elements with the specified tag name. By.tagName("a") Useful when the tag itself narrows the target sufficiently; a broad tag such as a can match many elements.
XPath Elements matching an XPath expression. By.xpath("//input[@value='f']") Useful for attributes and DOM relationships that are awkward to express with CSS. Selenium notes browser vendors typically do not performance-test XPath selectors, so do not treat XPath as universally slower based on that caveat alone.

Choose a locator that says what you mean

Prefer a unique ID when it is stable

Selenium’s locator practice guidance recommends a unique ID when available. Confirm that the ID belongs to the intended element and is not duplicated or generated unpredictably across page loads. A matching ID is only useful if it identifies the right element reliably.

Use CSS when there is no unique ID

Selenium’s guidance prefers a well-written CSS selector if unique IDs are unavailable. Choose an attribute or short selector that reflects the target, rather than relying on a long chain of incidental containers. CSS is not automatically the best choice for every page; the useful selector is the one that is specific, understandable, and stable for your application.

Use link text only for links

linkText and partialLinkText locate anchors by visible text. Exact link text is sensitive to wording changes; partial text can match several links and returns the first match in that case. If the page has repeated labels, scope the lookup or choose a more distinctive locator.

Use XPath for meaningful DOM relationships

XPath can express attribute conditions and relationships within the DOM. Prefer a readable expression tied to meaningful attributes or structure. Selenium notes that browser vendors typically do not performance-test XPath selectors; that is a qualification about testing, not a universal measured comparison against CSS.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Be careful with broad classes and tags

A class can be shared by many elements, and a tag-name locator can be very broad. Before using either with a singular lookup, verify that the page and locator together identify the target you expect.

Java examples for common elements

Suppose the page contains an input with id="fname", a field with name="newsletter", and an input with value="f". These Java examples show three different ways to locate them:

WebElement byId = driver.findElement(By.id("fname"));
WebElement byCss = driver.findElement(By.cssSelector("#fname"));
WebElement newsletter = driver.findElement(By.name("newsletter"));
WebElement femaleOption = driver.findElement(By.xpath("//input[@value='f']"));

The ID and CSS examples identify the same element if that ID is unique. The XPath example selects an input by its value attribute; make sure the page has the expected matching element before using a singular lookup.

What happens when a locator matches multiple elements?

Selenium provides singular and plural finding methods. In Java, findElement returns one matching element; findElements returns a collection of matches. Decide which behavior your test expects instead of assuming every locator is unique.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Use findElement when the intended target should be one element. Make the locator specific, and treat a missing or ambiguous match as a problem to investigate.
  • Use findElements when the page is expected to contain several matches, such as a set of links or rows; then inspect or iterate over the returned collection.
  • For partial link text, account for Selenium’s documented first-match behavior when more than one link contains the text.

For example, this code explicitly gathers all anchors and reports how many matched:

List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Matching links: " + links.size());

Use Selenium 4 relative locators for spatial relationships

Relative locators can help when the target is difficult to identify directly but its position relative to a known element is clear. Selenium 4 supports relationships such as above, below, left, right, and near. The reference explains that Selenium uses JavaScript getBoundingClientRect() to determine element size and position.

By emailLocator = RelativeLocator.with(By.tagName("input"))
    .above(By.id("password"));

This expresses that an input is above the element with ID password. Spatial relationships depend on page layout, so use them when position is meaningful to the test—not as a claim of greater stability than a direct semantic locator. Relative conditions can also be chained; for instance, a button can be located below one reference element and to the right of another.

A practical decision checklist

  • Uniqueness: Does this locator identify only the intended element, or should the test handle several matches?
  • Stability: Is it based on an application-maintained ID or useful attribute, rather than incidental markup likely to change?
  • Scope: Is this strategy valid for the target type? Link-text strategies require links.
  • Clarity: Can another maintainer understand why this element matches?
  • Expression: Does CSS express the target cleanly, or is an XPath or relative relationship genuinely helpful?
  • Binding: Does the syntax match your programming language and Selenium binding?

Troubleshooting locator failures

No element is found

Check that the page has loaded the expected content and that the locator matches the live DOM, including attribute values and text. Confirm that the target is in the page context your test is searching. If the element is conditional, wait for the relevant page state before locating it rather than assuming it already exists.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The locator identifies the wrong element

The selector may be too broad or may match an earlier element. Inspect how many nodes match, narrow the locator using a stable attribute or meaningful context, and avoid relying on the first result unless document order is part of the intended behavior.

A class-name lookup fails with multiple classes

By.className accepts one class name, not a compound class string. Use a CSS selector when the target must match more than one class, for example .card.featured, and verify the selector against the page.

Link-text lookup stops matching after a content change

Exact link text must match the visible wording. If wording is expected to vary, partial link text may be appropriate, but check for other links containing the same phrase; otherwise, prefer a stable attribute-based locator.

An XPath works but is hard to maintain

Replace long, position-dependent paths with a shorter expression based on a stable ID or attribute when possible. XPath is useful for relationships, but flexibility does not make every expression robust.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A relative locator changes with layout

Relative locators depend on element positions. If responsive layout or content changes move elements, use a direct semantic locator when one is available, or ensure the spatial relationship is genuinely part of the behavior being tested.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your task is to capture a page rather than interact with its DOM, ScreenshotNeo can return a screenshot or PDF with one GET request. The parameter names used by other screenshot APIs also work, which can make switching straightforward. See the ScreenshotNeo documentation for options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for 1,000 free screenshots a month, with no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Which Selenium locator should I try first?

Try a unique, stable ID if the application provides one. If not, Selenium’s guidance favors a well-written CSS selector.

Can Selenium find more than one element with a locator?

Yes. Use the plural finding method when you expect a collection; a locator does not inherently guarantee uniqueness.

Are relative locators available in Selenium 4?

Yes. They express spatial relationships such as above, below, left, right, and near.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.