Difference between findElements and findElement

Introduction

In this post, we will go through the differences between findElements and findElement methods of Selenium Webdriver. This question is often asked in the testing interviews for Webdriver automation testers. Both methods use By locating mechanism. By is an abstract class in Selenium API. By class provides mechanisms used to locate elements within a web document. We can create custom locating mechanisms by extending the By class. We can override the finding methods to provide custom locating
strategy.

SearchContext

 

Selenium API

 

//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 {

findElements()

Find all elements within the current page using the given mechanism. This method returns 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. In day-to-day Webdriver programming it is often we use these two methods.

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 returned 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()

findElement() returns the first matching element on the current page. 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"));

In the above example, the method returned a WebElement.In addition, when you are testing for non-existing elements on the web page, it is a best practice not to use this method.It’s always better to use findElements() method .findElement() should not be used to look for non-present elements on the page , use findElements() and assert zero-length response instead.