Skip to main content
SeleniumDecoded

Finding Elements

Master the fundamentals of locating web elements using Selenium's findElement and findElements methods.

Selenium 3 & 4 Stable

Finding elements is the foundation of web automation. Before you can click, type, or interact with anything on a page, you need to locate it first.

The Two Core Methods

Selenium provides two primary methods for finding elements:

MethodReturnsUse Case
findElement()Single WebElementWhen you expect exactly one match
findElements()List of WebElementsWhen you expect multiple matches

Finding a Single Element

Finding a Single Element
Selenium 3 & 4 Stable
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
// Find by ID
WebElement elementById = driver.findElement(By.id("username"));
// Find by name
WebElement elementByName = driver.findElement(By.name("email"));
// Find by class name
WebElement elementByClass = driver.findElement(By.className("submit-btn"));
// Find by CSS selector
WebElement elementByCss = driver.findElement(By.cssSelector("input[type='password']"));
// Find by XPath
WebElement elementByXpath = driver.findElement(By.xpath("//button[@id='login']"));
// Find by link text
WebElement elementByLink = driver.findElement(By.linkText("Sign Up"));
// Find by partial link text
WebElement elementByPartialLink = driver.findElement(By.partialLinkText("Sign"));
// Find by tag name
WebElement elementByTag = driver.findElement(By.tagName("h1"));
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://example.com")
# Find by ID
element_by_id = driver.find_element(By.ID, "username")
# Find by name
element_by_name = driver.find_element(By.NAME, "email")
# Find by class name
element_by_class = driver.find_element(By.CLASS_NAME, "submit-btn")
# Find by CSS selector
element_by_css = driver.find_element(By.CSS_SELECTOR, "input[type='password']")
# Find by XPath
element_by_xpath = driver.find_element(By.XPATH, "//button[@id='login']")
# Find by link text
element_by_link = driver.find_element(By.LINK_TEXT, "Sign Up")
# Find by partial link text
element_by_partial = driver.find_element(By.PARTIAL_LINK_TEXT, "Sign")
# Find by tag name
element_by_tag = driver.find_element(By.TAG_NAME, "h1")
const { Builder, By } = require('selenium-webdriver');
const driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://example.com');
// Find by ID
const elementById = await driver.findElement(By.id('username'));
// Find by name
const elementByName = await driver.findElement(By.name('email'));
// Find by class name
const elementByClass = await driver.findElement(By.className('submit-btn'));
// Find by CSS selector
const elementByCss = await driver.findElement(By.css("input[type='password']"));
// Find by XPath
const elementByXpath = await driver.findElement(By.xpath("//button[@id='login']"));
// Find by link text
const elementByLink = await driver.findElement(By.linkText('Sign Up'));
// Find by partial link text
const elementByPartial = await driver.findElement(By.partialLinkText('Sign'));
// Find by tag name
const elementByTag = await driver.findElement(By.tagName('h1'));
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://example.com");
// Find by ID
IWebElement elementById = driver.FindElement(By.Id("username"));
// Find by name
IWebElement elementByName = driver.FindElement(By.Name("email"));
// Find by class name
IWebElement elementByClass = driver.FindElement(By.ClassName("submit-btn"));
// Find by CSS selector
IWebElement elementByCss = driver.FindElement(By.CssSelector("input[type='password']"));
// Find by XPath
IWebElement elementByXpath = driver.FindElement(By.XPath("//button[@id='login']"));
// Find by link text
IWebElement elementByLink = driver.FindElement(By.LinkText("Sign Up"));
// Find by partial link text
IWebElement elementByPartial = driver.FindElement(By.PartialLinkText("Sign"));
// Find by tag name
IWebElement elementByTag = driver.FindElement(By.TagName("h1"));

Finding Multiple Elements

When you need to find all matching elements, use findElements:

Finding Multiple Elements
Selenium 3 & 4 Stable
import java.util.List;
// Find all links on the page
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Found " + allLinks.size() + " links");
// Find all items in a list
List<WebElement> listItems = driver.findElements(By.cssSelector("ul.menu li"));
// Iterate through elements
for (WebElement link : allLinks) {
System.out.println(link.getText());
}
// Find all buttons with a specific class
List<WebElement> buttons = driver.findElements(By.className("btn-primary"));
// Check if elements exist (returns empty list, never throws)
List<WebElement> results = driver.findElements(By.className("search-result"));
if (results.isEmpty()) {
System.out.println("No results found");
} else {
System.out.println("Found " + results.size() + " results");
}
# Find all links on the page
all_links = driver.find_elements(By.TAG_NAME, "a")
print(f"Found {len(all_links)} links")
# Find all items in a list
list_items = driver.find_elements(By.CSS_SELECTOR, "ul.menu li")
# Iterate through elements
for link in all_links:
print(link.text)
# Find all buttons with a specific class
buttons = driver.find_elements(By.CLASS_NAME, "btn-primary")
# Check if elements exist (returns empty list, never throws)
results = driver.find_elements(By.CLASS_NAME, "search-result")
if not results:
print("No results found")
else:
print(f"Found {len(results)} results")
// Find all links on the page
const allLinks = await driver.findElements(By.tagName('a'));
console.log(`Found ${allLinks.length} links`);
// Find all items in a list
const listItems = await driver.findElements(By.css('ul.menu li'));
// Iterate through elements
for (const link of allLinks) {
console.log(await link.getText());
}
// Find all buttons with a specific class
const buttons = await driver.findElements(By.className('btn-primary'));
// Check if elements exist (returns empty array, never throws)
const results = await driver.findElements(By.className('search-result'));
if (results.length === 0) {
console.log('No results found');
} else {
console.log(`Found ${results.length} results`);
}
using System.Collections.Generic;
// Find all links on the page
IList<IWebElement> allLinks = driver.FindElements(By.TagName("a"));
Console.WriteLine($"Found {allLinks.Count} links");
// Find all items in a list
IList<IWebElement> listItems = driver.FindElements(By.CssSelector("ul.menu li"));
// Iterate through elements
foreach (IWebElement link in allLinks)
{
Console.WriteLine(link.Text);
}
// Find all buttons with a specific class
IList<IWebElement> buttons = driver.FindElements(By.ClassName("btn-primary"));
// Check if elements exist (returns empty list, never throws)
IList<IWebElement> results = driver.FindElements(By.ClassName("search-result"));
if (results.Count == 0)
{
Console.WriteLine("No results found");
}
else
{
Console.WriteLine($"Found {results.Count} results");
}

Locator Strategy Priority

Use this order when choosing how to locate elements:

  1. ID - Most reliable, fastest
  2. Name - Good for form elements
  3. CSS Selector - Flexible and fast
  4. XPath - Most powerful, use when CSS can’t work
  5. Link Text - For anchor tags only
  6. Class Name - Often not unique
  7. Tag Name - Rarely unique enough

Handling NoSuchElementException

When findElement can’t find a match, it throws an exception:

Handling Element Not Found
Selenium 3 & 4 Stable
import org.openqa.selenium.NoSuchElementException;
try {
WebElement element = driver.findElement(By.id("nonexistent"));
element.click();
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
}
// Alternative: Check with findElements
List<WebElement> elements = driver.findElements(By.id("maybeExists"));
if (!elements.isEmpty()) {
elements.get(0).click();
}
from selenium.common.exceptions import NoSuchElementException
try:
element = driver.find_element(By.ID, "nonexistent")
element.click()
except NoSuchElementException as e:
print(f"Element not found: {e}")
# Alternative: Check with find_elements
elements = driver.find_elements(By.ID, "maybeExists")
if elements:
elements[0].click()
const { error } = require('selenium-webdriver');
try {
const element = await driver.findElement(By.id('nonexistent'));
await element.click();
} catch (e) {
if (e instanceof error.NoSuchElementError) {
console.log('Element not found:', e.message);
}
}
// Alternative: Check with findElements
const elements = await driver.findElements(By.id('maybeExists'));
if (elements.length > 0) {
await elements[0].click();
}
using OpenQA.Selenium;
try
{
IWebElement element = driver.FindElement(By.Id("nonexistent"));
element.Click();
}
catch (NoSuchElementException e)
{
Console.WriteLine($"Element not found: {e.Message}");
}
// Alternative: Check with FindElements
IList<IWebElement> elements = driver.FindElements(By.Id("maybeExists"));
if (elements.Count > 0)
{
elements[0].Click();
}

Finding Elements Within Elements

You can scope your search to find elements within a parent element:

Scoped Element Search
Selenium 3 & 4 Stable
// Find the parent container
WebElement container = driver.findElement(By.id("search-results"));
// Find elements within the container
List<WebElement> items = container.findElements(By.className("result-item"));
// Find a specific element within
WebElement firstTitle = container.findElement(By.cssSelector("h3.title"));
# Find the parent container
container = driver.find_element(By.ID, "search-results")
# Find elements within the container
items = container.find_elements(By.CLASS_NAME, "result-item")
# Find a specific element within
first_title = container.find_element(By.CSS_SELECTOR, "h3.title")
// Find the parent container
const container = await driver.findElement(By.id('search-results'));
// Find elements within the container
const items = await container.findElements(By.className('result-item'));
// Find a specific element within
const firstTitle = await container.findElement(By.css('h3.title'));
// Find the parent container
IWebElement container = driver.FindElement(By.Id("search-results"));
// Find elements within the container
IList<IWebElement> items = container.FindElements(By.ClassName("result-item"));
// Find a specific element within
IWebElement firstTitle = container.FindElement(By.CssSelector("h3.title"));

Best Practices

  1. Prefer stable locators - IDs and data-testid attributes are best
  2. Avoid brittle locators - Positions, indexes, and auto-generated classes change
  3. Use explicit waits - Don’t assume elements are immediately available
  4. Scope when possible - Finding within a parent is faster and more reliable
  5. Add data-testid attributes - Work with developers to add test-friendly attributes

Next Steps

Now that you know how to find elements, learn about: