FindElement And FindElements Methods Of Selenium WebDriver
Need of FindElement/FindElements Command :
Whenever you want to interact with a web page, we require a user to locate the web elements. Selenium WebDriver defines two methods for identifying the elements, they are findElement and findElements.
findElement : This command is used to uniquely identify a web element within the web page.
findElements : This command is used to uniquely identify the list of web elements within the web page.
Selenium FindElement Command :
Find Element command takes in the By object as a parameter and returns an object of type WebElement. By object can be used with various locator strategies such as:
- ID
- Name
- Class Name
- Tag Name
- Link Text
- Partial Link Text
- XPath
Syntax
WebElement elementName = driver.findElement(By.LocatorStrategy("LocatorValue"));
Example: WebElement login = driver.findElement(By.linkText("Login"));
Selenium FindElements Command :
Selenium findElements command takes in By object as the parameter and returns a list of web elements.
Syntax
List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));
Example: List<WebElement> listOfElements = driver.findElements(By.xpath("//div"));
Difference Between FindElement and FindElements Methods :
Topic |
FindElement |
FindElements |
1. Use |
This command is used to access any single element on the web page. |
This command is used to uniquely identify the list of web elements within the web page. |
2. Return Type |
WebElement |
List of web elements |
3. Returns |
Returns the first most web element if there are multiple web elements found with the same locator. |
Returns the list of web elements whose match the locator strategy. |
4. Exception |
It will throw NoSuchElementException when it fails to identify the element. |
If the element doesn’t exist on the page then, then it will return value with an empty list. |