findElement vs findElements in Selenium Java
Both findElement() and findElements() are methods of the WebDriver and WebElement interfaces used to locate elements on a web page, but they behave differently.
1. findElement(By locator)
Returns a single WebElement that matches the first occurrence.
Throws
NoSuchElementExceptionif the element is not found.
Syntax:
WebElement element = driver.findElement(By.id("username"));
2. findElements(By locator)
Returns a List of WebElements matching the locator.
Returns an empty list if no elements are found (does NOT throw an exception).
Syntax:
List<WebElement> elements = driver.findElements(By.tagName("a"));
Java Example: findElement() vs findElements()
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; public class FindElementVsFindElements { public static void main(String[] args) { // Set path to chromedriver System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); // Initialize Chrome WebDriver WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); // Open website driver.get("https://www.google.com"); // ===== findElement() Example ===== WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("Selenium findElement vs findElements"); System.out.println("Search box found using findElement()"); // ===== findElements() Example ===== List<WebElement> allLinks = driver.findElements(By.tagName("a")); System.out.println("Total links found using findElements(): " + allLinks.size()); // Print first 5 link texts (if available) for (int i = 0; i < Math.min(5, allLinks.size()); i++) { String text = allLinks.get(i).getText(); System.out.println("Link " + (i + 1) + ": " + text); } // Close browser driver.quit(); } }
No comments:
Post a Comment