3/29/17

Difference between findElement() and findElements()

In this post, we will learn the difference between findElement() and findElements(). These are the important methods  which are used for finding elements on the WebPage.

Usage of findElement():

This is used to find the WebElement  like Button, checkbox,radio button etc. on the page.The different locator (id,name,xpath etc.) are used within it to find the elements.
Syntax:
driver.findElement(By.xpath(“XPATH expression”));
driver.findElement(By.id(“Id of element”));
driver.findElement(By.name(“name of element”));

As an example, we will try to locate the ‘Google search’button on the Google page. We will use its name attribute as it is unique(shown in the figure below).
isdisplayed in selenium
We use ‘isDisplayed()’ method, which returns true value if it finds the element else false. We are printing true or false result in the console by using ‘System.out.println’.
Output: true

Usage of findElements(): 

The method fincElements() returns a list of WebElements on the page. We can work over that list according to our need.
Suppose, we need to count the no. of links on the Google Page. As we know link is represented by tag ‘a’ in html. So, we will use the method ‘tagName’ to count the total no. of links.
Total links : 46
You might be surprised after seeing the output 46, but when we look at google page , it does not seem to have 46 links. You dont need to worry about that , there are some hidden links which are not visible to us but selenium can detect them. That’s why it has returned count as 46.

Google Q&A Forum