Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 35 ยท Finding Elements

Locators: id, name, class and tag

Find elements with Selenium's simplest locators: By.ID, NAME, CLASS_NAME and TAG_NAME. Learn find_element versus find_elements and NoSuchElementException.

Every Selenium test has the same problem to solve before it can do anything: which element do I mean? A locator is the answer. It is a pair of values, a strategy (how to search) and a value (what to search for), that tells the driver which element on the page you want.

This lesson covers the four simplest strategies, id, name, class name and tag name, and the two methods you use to apply them. Later lessons add the powerful ones: CSS selectors and XPath. The real Selenium needs a browser, so the Selenium code here is read-only. The runnable stand-ins use the browser's own DOM functions to model how each strategy searches.

The shape of a locator

A locator has two parts

Strategy By.ID, By.NAME, By.CLASS_NAME, By.TAG_NAME and more.
Value The text to match, like "email".

driver.find_element(strategy, value)

1 / 2

Here is a small page to search. Imagine it is open in the browser:

HTML
<form id="login-form">
  <input id="email" name="email" class="field required" type="email">
  <input id="password" name="password" class="field" type="password">
  <button class="btn primary" type="submit">Sign in</button>
</form>

The four strategies

In Python you import By and pass a strategy and a value:

Python
from selenium.webdriver.common.by import By

driver.find_element(By.ID, "email")            # id="email"
driver.find_element(By.NAME, "password")       # name="password"
driver.find_element(By.CLASS_NAME, "primary")  # class contains "primary"
driver.find_element(By.TAG_NAME, "button")     # first <button>

Java uses factory methods on By:

Java
driver.findElement(By.id("email"));
driver.findElement(By.name("password"));
driver.findElement(By.className("primary"));
driver.findElement(By.tagName("button"));
Strategy Matches Notes
ID The id attribute Ids should be unique on a page, so this is the most precise and the fastest to read
NAME The name attribute Common on form fields; several elements can share a name (radio buttons do)
CLASS_NAME One class name from the class attribute Takes a single class. A value with spaces such as "btn primary" does not work as you might expect. Use a CSS selector for several classes
TAG_NAME The element type, like button or h1 Usually too broad on its own; best for lists, like all a or li elements

Older tutorials use find_element_by_id(...). Those methods were removed from the Python binding in Selenium 4. Always use find_element(By.ID, ...).

find_element and find_elements

The two methods behave very differently when nothing matches, and that difference shapes a lot of test code.

  • find_element returns one element: the first match in document order. If there is no match it raises NoSuchElementException.
  • find_elements returns a list of all matches. If nothing matches it returns an empty list and does not raise.
Python
from selenium.common.exceptions import NoSuchElementException

# raises if missing
button = driver.find_element(By.TAG_NAME, "button")

# safe way to ask "is it there?"
errors = driver.find_elements(By.CLASS_NAME, "error-message")
if errors:
    print("The page shows an error:", errors[0].text)
else:
    print("No error shown")

# or catch the exception
try:
    driver.find_element(By.ID, "promo-banner")
except NoSuchElementException:
    print("No banner today")

Use find_element when the element must exist (a missing element is then a real test failure with a clear message). Use find_elements when "not there" is a legitimate answer, or when you want every row in a list. Checking len(driver.find_elements(...)) == 0 is the standard way to assert that something is absent.

A stand-in: strategies on a sample DOM

The browser that runs this page has a DOM too, so the stand-in builds the sample form with document.body.innerHTML and then implements find_element and find_elements using DOM functions. It is not Selenium: there is no driver, only the same searching rules.

JS find_element and find_elements on a sample page

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the last three lines of output: the same missing id gives an empty list with find_elements and an exception with find_element.

Choosing between them

A quick rule of thumb for these four strategies:

  1. If the element has a stable id, use it. It is short, unambiguous and survives most layout changes.
  2. For form fields without an id, name is usually next best.
  3. Use CLASS_NAME only when the class describes what the element is (error-message), not how it looks (mt-4 text-red). Styling classes change often.
  4. Use TAG_NAME mainly with find_elements, to count or loop over items.

When none of these is precise enough, you need CSS selectors or XPath. A deeper look at which locators last longest comes in Choosing Stable Locators.

Searching inside an element

find_element also exists on elements, and then it searches only inside that element:

Python
form = driver.find_element(By.ID, "login-form")
email_field = form.find_element(By.NAME, "email")   # only looks inside the form
buttons = form.find_elements(By.TAG_NAME, "button")

This keeps locators short and avoids matching a similarly named element elsewhere on the page.

A second stand-in: searching inside a container

The model below shows scoped searching. Two forms on the page both have an email field. Searching the whole document finds the first one, while searching inside a chosen form finds the right one.

JS Scoped searches inside an element

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does find_elements return when nothing matches?

    find_elements never raises for a missing match. It returns an empty list, which makes it the right tool for asking whether something is present.
  2. 2. Which exception does find_element raise when no element matches?

    NoSuchElementException is what the Python binding raises when the driver replies with the no such element error.
  3. 3. Why is By.CLASS_NAME with the value "btn primary" a bad idea?

    CLASS_NAME expects one class. For an element with several classes, a CSS selector such as button.btn.primary is the correct tool.
  4. 4. What does form.find_element(...) do when called on an element?

    Calling find_element on a WebElement scopes the search to that element's descendants, which keeps locators short and precise.

Summary

  • A locator is a strategy plus a value; the four basic strategies are ID, NAME, CLASS_NAME and TAG_NAME.
  • find_element returns the first match or raises NoSuchElementException; find_elements returns a list that may be empty.
  • CLASS_NAME takes one class only; use CSS for combinations.
  • Prefer a stable id, then name; use class and tag names with care.
  • Calling find_element on an element searches only inside it.
  • The DOM functions in the stand-ins model how each strategy searches; they are not Selenium.

Continue with the most flexible everyday locator in CSS Selector Locators.