Site icon TestingDocs.com

Difference between findElements and findElement [ 2024 ]

Difference between findElements and findElement

This post will discuss the differences between Selenium WebDriver’s findElements and findElement methods.

Both functions are used to locate and find the web elements on the web page. Both methods use the By abstract class locating mechanism in the Selenium WebDriver API. The By class provides mechanisms for locating elements within a web document.

SearchContext

 

findElements and findElement

 

//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() Method

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.

A sample example of the method used is shown below snippet:

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

findElements() Method

Find all elements within the current page using the given mechanism. This method returns all the elements the locator points as a List, which may return zero or more Web elements. Note that if the locating mechanism from By instance doesn’t find any findElements() method, it returns an empty list. Unlike findElement(), it 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 implicitly wait for this method, it will return items found in the collection. Finally, if the timeout is reached, it will return an empty list.

findElement() should not be used to look up non-present elements on the web page. Using the method, you should use findElements() and assert a zero-length response.

Selenium WebDriver Tutorials on this website can be found at:

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

Exit mobile version