In Selenium WebDriver, both findElement() and findElements() are used to locate elements on a web page, but they have distinct behaviors and use cases.
1. findElement()
The findElement() method is used to find a single web element that matches the specified locator.
Syntax:
WebElement element = driver.findElement(By.locator("value"));
Key Points:
- Returns the first matching element on the page.
- If the element is not found, it throws a NoSuchElementException.
- Used when you expect only one unique element to be present.
Example:
WebElement loginButton = driver.findElement(By.id("loginBtn"));
loginButton.click();
If there are multiple elements matching the locator, only the first one will be returned.
2. findElements()
The findElements() method is used to find multiple elements matching a locator.
Syntax:
List<WebElement> elements = driver.findElements(By.locator("value"));
Key Points:
- Returns a List containing all matching elements.
- If no matching elements are found, it returns an empty list instead of throwing an exception.
- Used when multiple elements might be present, such as a list of links, buttons, or table rows.
Example:
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + links.size());
If there are no <a>
elements on the page, it will return an empty list (size = 0
).
3. Difference Between findElement() and findElements()
Feature | findElement() | findElements() |
---|---|---|
Return Type | Single WebElement |
List<WebElement> (multiple elements) |
When No Match? | Throws NoSuchElementException |
Returns an empty list (size = 0 ) |
Use Case | When only one element is expected | When multiple elements might be present |
4. Handling NoSuchElementException in findElement()
Since findElement() throws an exception if the element is not found, you should handle it using a try-catch
block:
try {
WebElement element = driver.findElement(By.id("nonExistingElement"));
element.click();
} catch (NoSuchElementException e) {
System.out.println("Element not found!");
}
5. Real-World Example: Navigating Through a List of Elements
If you want to click on a specific link from a list, findElements() is useful:
List<WebElement> menuItems = driver.findElements(By.cssSelector(".menu-item"));
for (WebElement item : menuItems) {
if (item.getText().equals("Contact Us")) {
item.click();
break;
}
}
This ensures we select the right link dynamically.
6. When to Use Which?
Scenario | Method to Use |
---|---|
Click on a single button/link | findElement() |
Get the first matching element | findElement() |
Count the number of elements | findElements().size() |
Retrieve all links in a section | findElements() |
Verify if an element exists | findElements().isEmpty() |
Conclusion
- Use findElement() when you are sure that only one element exists.
- Use findElements() when you need to find multiple elements or avoid exceptions.