Answer
findElement() vs findElements()
findElement()
Java
// Returns ONE WebElement
// Throws NoSuchElementException if NOT found
WebElement email = driver.findElement(By.id("email"));
// Usage
email.sendKeys("test@email.com");
email.click();
String text = email.getText();
// Always throws if missing — use try/catch if optional
try {
WebElement optional = driver.findElement(By.id("popup"));
optional.click();
} catch (NoSuchElementException e) {
// element not present — that's ok
}
findElements()
Java
// Returns List<WebElement>
// Returns EMPTY LIST if nothing found — NEVER throws
List<WebElement> rows = driver.findElements(By.cssSelector("table tr"));
// Safe size check
System.out.println("Row count: " + rows.size());
// Iterate all elements
for (WebElement row : rows) {
System.out.println(row.getText());
}
// Check if element exists WITHOUT exception
boolean isDisplayed = !driver.findElements(By.id("error-msg")).isEmpty();
// isEmpty() returns true when element not found
Comparison Table
findElement() | findElements() | |
|---|---|---|
| Returns | Single WebElement | List<WebElement> |
| If not found | NoSuchElementException | Empty list [] |
| Exception risk | Yes | No |
| Best for | Required unique elements | Multiple/optional elements |
| Check existence | No (use try/catch) | .isEmpty() |
| First match | Implicit | Use .get(0) |
Common Patterns
Java
// 1. Get text from all product names
List<WebElement> names = driver.findElements(By.className("product-name"));
List<String> nameList = names.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
// 2. Count search results
int count = driver.findElements(By.cssSelector(".result-item")).size();
Assert.assertTrue(count > 0, "No results found");
// 3. Check element does NOT exist
List<WebElement> ads = driver.findElements(By.id("ad-banner"));
Assert.assertTrue(ads.isEmpty(), "Ad banner should not appear after login");
// 4. Click the 3rd item in a list
List<WebElement> items = driver.findElements(By.cssSelector(".menu-item"));
items.get(2).click(); // index 2 = 3rd item
// 5. Wait for multiple elements
List<WebElement> cards = wait.until(
ExpectedConditions.numberOfElementsToBeMoreThan(
By.cssSelector(".card"), 0));
