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:
| Method | Returns | Use Case |
|---|---|---|
findElement() | Single WebElement | When you expect exactly one match |
findElements() | List of WebElements | When 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 IDWebElement elementById = driver.findElement(By.id("username"));
// Find by nameWebElement elementByName = driver.findElement(By.name("email"));
// Find by class nameWebElement elementByClass = driver.findElement(By.className("submit-btn"));
// Find by CSS selectorWebElement elementByCss = driver.findElement(By.cssSelector("input[type='password']"));
// Find by XPathWebElement elementByXpath = driver.findElement(By.xpath("//button[@id='login']"));
// Find by link textWebElement elementByLink = driver.findElement(By.linkText("Sign Up"));
// Find by partial link textWebElement elementByPartialLink = driver.findElement(By.partialLinkText("Sign"));
// Find by tag nameWebElement elementByTag = driver.findElement(By.tagName("h1"));from selenium import webdriverfrom selenium.webdriver.common.by import By
driver = webdriver.Chrome()driver.get("https://example.com")
# Find by IDelement_by_id = driver.find_element(By.ID, "username")
# Find by nameelement_by_name = driver.find_element(By.NAME, "email")
# Find by class nameelement_by_class = driver.find_element(By.CLASS_NAME, "submit-btn")
# Find by CSS selectorelement_by_css = driver.find_element(By.CSS_SELECTOR, "input[type='password']")
# Find by XPathelement_by_xpath = driver.find_element(By.XPATH, "//button[@id='login']")
# Find by link textelement_by_link = driver.find_element(By.LINK_TEXT, "Sign Up")
# Find by partial link textelement_by_partial = driver.find_element(By.PARTIAL_LINK_TEXT, "Sign")
# Find by tag nameelement_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 IDconst elementById = await driver.findElement(By.id('username'));
// Find by nameconst elementByName = await driver.findElement(By.name('email'));
// Find by class nameconst elementByClass = await driver.findElement(By.className('submit-btn'));
// Find by CSS selectorconst elementByCss = await driver.findElement(By.css("input[type='password']"));
// Find by XPathconst elementByXpath = await driver.findElement(By.xpath("//button[@id='login']"));
// Find by link textconst elementByLink = await driver.findElement(By.linkText('Sign Up'));
// Find by partial link textconst elementByPartial = await driver.findElement(By.partialLinkText('Sign'));
// Find by tag nameconst 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 IDIWebElement elementById = driver.FindElement(By.Id("username"));
// Find by nameIWebElement elementByName = driver.FindElement(By.Name("email"));
// Find by class nameIWebElement elementByClass = driver.FindElement(By.ClassName("submit-btn"));
// Find by CSS selectorIWebElement elementByCss = driver.FindElement(By.CssSelector("input[type='password']"));
// Find by XPathIWebElement elementByXpath = driver.FindElement(By.XPath("//button[@id='login']"));
// Find by link textIWebElement elementByLink = driver.FindElement(By.LinkText("Sign Up"));
// Find by partial link textIWebElement elementByPartial = driver.FindElement(By.PartialLinkText("Sign"));
// Find by tag nameIWebElement 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 pageList<WebElement> allLinks = driver.findElements(By.tagName("a"));System.out.println("Found " + allLinks.size() + " links");
// Find all items in a listList<WebElement> listItems = driver.findElements(By.cssSelector("ul.menu li"));
// Iterate through elementsfor (WebElement link : allLinks) { System.out.println(link.getText());}
// Find all buttons with a specific classList<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 pageall_links = driver.find_elements(By.TAG_NAME, "a")print(f"Found {len(all_links)} links")
# Find all items in a listlist_items = driver.find_elements(By.CSS_SELECTOR, "ul.menu li")
# Iterate through elementsfor link in all_links: print(link.text)
# Find all buttons with a specific classbuttons = 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 pageconst allLinks = await driver.findElements(By.tagName('a'));console.log(`Found ${allLinks.length} links`);
// Find all items in a listconst listItems = await driver.findElements(By.css('ul.menu li'));
// Iterate through elementsfor (const link of allLinks) { console.log(await link.getText());}
// Find all buttons with a specific classconst 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 pageIList<IWebElement> allLinks = driver.FindElements(By.TagName("a"));Console.WriteLine($"Found {allLinks.Count} links");
// Find all items in a listIList<IWebElement> listItems = driver.FindElements(By.CssSelector("ul.menu li"));
// Iterate through elementsforeach (IWebElement link in allLinks){ Console.WriteLine(link.Text);}
// Find all buttons with a specific classIList<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:
- ID - Most reliable, fastest
- Name - Good for form elements
- CSS Selector - Flexible and fast
- XPath - Most powerful, use when CSS can’t work
- Link Text - For anchor tags only
- Class Name - Often not unique
- 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 findElementsList<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_elementselements = 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 findElementsconst 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 FindElementsIList<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 containerWebElement container = driver.findElement(By.id("search-results"));
// Find elements within the containerList<WebElement> items = container.findElements(By.className("result-item"));
// Find a specific element withinWebElement firstTitle = container.findElement(By.cssSelector("h3.title"));# Find the parent containercontainer = driver.find_element(By.ID, "search-results")
# Find elements within the containeritems = container.find_elements(By.CLASS_NAME, "result-item")
# Find a specific element withinfirst_title = container.find_element(By.CSS_SELECTOR, "h3.title")// Find the parent containerconst container = await driver.findElement(By.id('search-results'));
// Find elements within the containerconst items = await container.findElements(By.className('result-item'));
// Find a specific element withinconst firstTitle = await container.findElement(By.css('h3.title'));// Find the parent containerIWebElement container = driver.FindElement(By.Id("search-results"));
// Find elements within the containerIList<IWebElement> items = container.FindElements(By.ClassName("result-item"));
// Find a specific element withinIWebElement firstTitle = container.FindElement(By.CssSelector("h3.title"));Best Practices
- Prefer stable locators - IDs and data-testid attributes are best
- Avoid brittle locators - Positions, indexes, and auto-generated classes change
- Use explicit waits - Don’t assume elements are immediately available
- Scope when possible - Finding within a parent is faster and more reliable
- Add data-testid attributes - Work with developers to add test-friendly attributes
Next Steps
Now that you know how to find elements, learn about:
- CSS Selectors - Master CSS selector syntax
- XPath Basics - Learn XPath for complex scenarios
- Click and Type - Interact with found elements