Quality Testing

Quality is delighting customers

What is the difference between findElement and findElements in Selenium?

Hi, Can any one explain the difference between findElement and findElements with example.

Views: 302

Reply to This

Replies to This Discussion

findElement - it will return the first Webelement find by the locator specified.
example = say you wanted to click on some element

findElements = this returns a list of webelement found by the given selector.
example = say you wanted to get all items in a table then wanted to perform operation on them one by one.

As per suggestions from software testing company, find element is most commonly used as compared to the find elements method. however, both are the methods available in the Selenium WebDriver, used to locate elements on the web pages while automating the web application. 

The purpose of both methods is the same but there's a difference between how they work. 

Find element method: It returns the first matching web element from the webpage & when it fails to find any matching element then it throws NoSuchElementException. 

Syntax: driver.findElement(By.xpath("Value of Xpath"));

However, suppose when there are multiple elements with the same locator, but it will return the first element it finds but you may need to interact with say seconds or any other element other than first. Then it comes time to use the find elements. 

Find elements method: It returns all of the matching elements from the webpage, & we can store those elements & traverse to the desired element. Also when no element is found it returns an empty list instead of throwing an exception.

Syntax: driver.findElements(By.xpath("Value of Xpath"));

Mostly we store the find elements into the list. 

Like : List link = driver.findElements(By.xpath("Value of Xpath"));

If you have any doubts please do let me know.





TTWT Magazine





© 2021   Created by Quality Testing.   Powered by

Badges  |  Report an Issue  |  Terms of Service