Site icon TestingDocs.com

Difference between findElements and findElement

Introduction

In this post, we will go through the differences between findElements and findElement methods of Selenium Webdriver. Both methods use By abstract class locating mechanism in Selenium WebDriver API. By class provides mechanisms used to locate elements within a web document.

SearchContext

 

 

//SearchContext Interface
public interface SearchContext {
  List<WebElement> findElements(By paramBy);
  
  WebElement findElement(By paramBy);
}

WebDriver interface implements the SearchContext Interface. Locating elements on a webpage uses these methods.

public interface WebDriver extends SearchContext {

 

findElement()

findElement() should be used when we try to find a single element on the web page. This method always returns the first matching element. The method throws NoSuchElementException if no matching elements are found.

WebElement findElement(By by);

This method is affected by the implicit wait time in force at the time of execution. The findElement() invocation will return a matching row or try again repeatedly until the configured timeout is reached.

Sample example of the method used as shown below snippet:

 driver.get("https://www.bing.com/");
 WebElement element = driver.findElement(By.id("sb_form_q"));

 

findElements()

Find all elements within the current page using the given mechanism. This method returns a List so it may return zero or more Web elements. Note that if the locating mechanism from By instance doesn’t find any findElements() method returns an empty list. Unlike, findElement() is doesn’t throw an exception.

List<WebElement> findElements(By by);

A sample example of finding the links on a web page is as shown below code snippet :

List<WebElement> links = driver.findElements(By.tagName("a"));

In the above example, the method returns a List<WebElement>. This method is affected by the implicit wait times in force at the time of execution. When we use implicitly wait for this method will return items found in the collection. At last, if the timeout is reached it will return an empty list.

findElement() should not be used to look up for non-present elements on the web page. It’s recommended to  use findElements() and assert for zero-length response from the method.

Selenium WebDriver Tutorials on this website can be found at:

https://www.testingdocs.com/selenium-webdriver-tutorial

For more details on the Selenium, visit the official website at:

https://www.selenium.dev/

Exit mobile version