We have seen some examples of webdriver's findElement() in previous posts. Selenium WebDriver has one more related methods finding Elements. In this section, we will disuss on what is the difference between findElement and findElements methods in Selenium WebDriver.
findElement() method
- findElement() method is useful to locate targeted single element.
- If targeted element is not found on the page then it will throw NoSuchElementException.
- findElement() method accepts a Parameter and which is By Object. By is the mechanism used to locate elements within a document with the help of locator value.
findElements() method
- findElements() method will return list of all the matching elements from current page as per given element locator mechanism.
- If not found any element on current page as per given element locator mechanism, it will return empty list.
- findElement() method also accepts a Parameter and which is By Object. By is the mechanism used to locate elements within a document with the help of locator value.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class test { public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "./lib/geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("http://localhost:7000/amc/"); //driver.findElement will return one element WebElement Name = driver.findElement(By.id("name")); System.out.print(Name.getAttribute("id") + " - " + Name.getText()); //driver.findElements will return multiple webelements List<WebElement> options = driver.findElements(By.xpath("//option")); System.out.println(options.size()); for (int i = 0; i <= options.size(); i++) { String str = options.get(i).getAttribute("id") + " - " + options.get(i).getText(); System.out.println(str); } driver.close(); } } |
Really blog is very informative and easy to understand
ReplyDelete