Difference between findElement() and findElements()
In the previous post, we have seen about WebDriver get() and navigate() methods. 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.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).
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’.
public class ExampleFindElement { private static WebDriver driver; public static void main(String[] args) throws InterruptedException { driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://google.com"); System.out.println(driver.findElement(By.name("btnK")).isDisplayed()); } }
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.
public class ExampleFindElements { private static WebDriver driver; public static void main(String[] args) throws InterruptedException { driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://google.com"); List<WebElement> totalLinks = driver.findElements(By.tagName("a")); System.out.println("Total links : "+totalLinks.size()); // total links } }
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.