Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk5 min

How to Use ID Locators in Selenium WebDriver

Find page elements by their HTML ID in Selenium WebDriver, with Java and Python examples, guidance on duplicate IDs, and the difference between ID and CSS locators.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Selenium’s dedicated ID locator with the element’s raw HTML ID value: in Java, driver.findElement(By.id("lname")); in Python, driver.find_element(By.ID, "lname"). Do not add #—that prefix is for a CSS selector. Use a singular lookup when you expect one match and a plural lookup when you need to inspect all matches or handle none. Selenium says IDs should generally be unique, but duplicate IDs can occur in page markup.

What an ID locator does

An HTML element may include an ID attribute such as id="lname". Selenium’s ID strategy matches that attribute to the value you supply. The locator value is lname, not #lname. Selenium’s official locator guide shows ID locator examples in Java, Python, JavaScript, C#, and Ruby.

As an Amazon Associate I earn from qualifying purchases.

For Java, the dedicated locator is By.id("lname"). In Python, pass By.ID and the raw value to find_element. These are binding-specific method names for the same basic task.

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

Use the locator in a test

  1. Open the page under test. Navigate with the WebDriver instance your test already uses.
  2. Identify the rendered ID. Inspect the page’s DOM and confirm the target element has an ID, for example id="lname".
  3. Locate it using the raw value. Choose the language-specific example below.
  4. Use the returned element. Interact with it or assert the relevant state for your test.

Java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

// Assumes driver is an initialized WebDriver and the page is loaded.
WebElement lastName = driver.findElement(By.id("lname"));

Python

from selenium.webdriver.common.by import By

# Assumes driver is an initialized WebDriver and the page is loaded.
last_name = driver.find_element(By.ID, "lname")

The examples show the locator call, not a complete browser setup: driver initialization and navigation depend on the test project. Selenium’s guide demonstrates locating an element and checking its attributes; no particular assertion is appropriate until you know what the page should do.

Choose one-result or all-results lookup

The lookup method affects what your test receives. According to Selenium’s element-finding guide, findElement returns the first matching element in the current search context. findElements returns all matches, or an empty list when there are none.

Java: one expected match

WebElement lastName = driver.findElement(By.id("lname"));

Java: inspect all matches

List<WebElement> matches = driver.findElements(By.id("lname"));
if (matches.size() != 1) {
    throw new AssertionError("Expected exactly one element with id=lname, found " + matches.size());
}
WebElement lastName = matches.get(0);

This example checks uniqueness explicitly rather than silently accepting the first result. Import java.util.List if it is not already imported.

Python: one expected match

last_name = driver.find_element(By.ID, "lname")

Python: inspect all matches

matches = driver.find_elements(By.ID, "lname")
if len(matches) != 1:
    raise AssertionError(f"Expected exactly one element with id=lname, found {len(matches)}")
last_name = matches[0]

Use the plural form when zero matches is a valid outcome to handle, or when the test must detect duplicate IDs. If the test requires exactly one element, assert that count before using a result.

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

Distinguish an ID locator from a CSS selector

The dedicated ID strategy takes the unprefixed ID value. CSS uses a hash-prefixed selector. Both can target an element with ID fname, but the syntax belongs to different locator strategies:

  • By.id("fname") — dedicated ID locator; pass fname.
  • By.cssSelector("#fname") — CSS selector; include #.

Putting # inside By.id asks Selenium to match an ID containing that character, rather than expressing CSS ID syntax. The JavaScript API reference describes its ID locator implementation using a CSS selector of the form *[id="$ID"]; that is an implementation detail of that API, not a universal promise about every language binding. See Selenium’s JavaScript By API reference.

When to choose ID or another locator

An ID is a straightforward choice when the target has a suitable ID and the test expects the element to be unambiguous. Selenium’s locator guide also lists class name, CSS selector, name, link text, partial link text, tag name, and XPath. Choose based on the page’s markup and what the test needs to identify; no single strategy is right for every page.

For maintainable tests, select locators deliberately and keep locator choices organized rather than scattering them through lookup logic. Selenium’s locator best-practices guidance discusses choosing and managing locators.

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

Troubleshoot common ID lookup problems

The lookup does not find an element

  • Check the exact attribute value. Inspect the rendered DOM and confirm the element’s ID spelling and capitalization; pass the attribute value without a CSS prefix.
  • Confirm the page and search context. The lookup searches the current context, so ensure the expected page or context is active before locating the element.
  • Decide whether absence is expected. A singular lookup is intended for an expected match; use plural lookup if your test needs to treat no matches as an empty collection.

The singular lookup finds the wrong element

Check for duplicate IDs. Selenium describes IDs as generally unique, but the page’s actual markup may not follow that expectation. A singular lookup returns the first match; use findElements and assert that the count is one if uniqueness is part of the test.

The locator includes a hash sign

Remove # when using By.id or By.ID. Keep it only when the locator strategy is CSS, such as By.cssSelector("#fname").

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 goal is a page image rather than an interactive Selenium test, ScreenshotNeo can return a screenshot or PDF from one GET request. Its API supports PNG, JPEG, or WebP screenshots and PDFs; the example below saves the response as WebP.

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

See the ScreenshotNeo API documentation for request options. ScreenshotNeo accepts cookie 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, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and whether the capture was billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

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

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.

Frequently Asked Questions

Does Selenium’s ID locator use the element’s id attribute?

Yes. It matches the ID attribute to the value supplied to the ID locator.

Does CSS use the same syntax as By.id?

No. The dedicated ID locator takes the raw value; a CSS selector uses the hash-prefixed form, such as #fname.

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.

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.

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
PC Slower Than It Used to Be?Free scan - under a minute
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.