Difference between findElement and findElements in Selenium WebDriver

We have used the methods findElement and findElements in multiple scenarios, but there are more than one differences between these two methods.

Both the methods are used to locate the element(s) on the webpage and any of the 8 locators can be used with the same.

findElement : WebElement findElement(By by) 

  • The method is used to find a single element on the webpage.
  • The method returns WebElement.
  • If more than one element is found matching the search criteria, then the first element will be returned.
  • If no element is found on the webpage, the method throws NoSuchElementFound exception.
  • We can apply any of the WebElement methods on the returned element.

findElements : List<WebElement> findElements(By by)

  • The method is used to find a group of elements on the webpage.
  • The method returns  List<WebElement> i.e. a list of elements.
  • If single element is found matching the search criteria, then the list containing one element will be returned.
  • If no element is found on the webpage, the method returns empty list of WebElements.
  • Since, we get an array list of all web elements, we can not apply WebElement’s method directly, instead we need to iterate through the array list of elements and perform operation of WebElement in iteration (We can apply any of the List methods).

 

Both the methods are declared in WebElement interface, but its implementation is provided in RemoteWebElement class which implements WebElement interface.

WebDriver driver = new FirefoxDriver();
driver.get(“https://seleniumlive.wordpress.com/”);

// using findElement method

WebElement elem = driver.findElement(By.xpath(“//h1[@class=’site-title’]”));

// getting text of the unique H1 webelement using getText method

System.out.println(elem.getText());

// using findElements method to get all the images on the webpage

List<WebElement> listOfImages = driver.findElements(By.tagName(“img”));

// getting size of list i.e. no. of images on webpage

System.out.println(listOfImages.size());

 

Advertisements

#findelement, #findelements