Why Do You Need FindElement/s Command?
Interaction with a web page requires a user to locate the web element.
FindElement command is used to uniquely identify a (one) web element within the web page.
FindElements command is used to uniquely identify the list of web elements within the web page.
There are multiple ways to uniquely identify a web element within the web page such as ID, Name, Class Name, Link Text, Partial Link Text, Tag Name and XPath.
FindElement Command Syntax
Selenium FindElement command takes in the By object as the parameter and returns an object of type list WebElement in Selenium. By object in turn can be used with various locator strategies such as find element by ID Selenium, Name, Class Name, XPath etc. Below is the syntax of FindElement command in Selenium web driver.
WebElement elementName = driver.findElement(By.LocatorStrategy("LocatorValue"));
Locator Strategy can be any of the following values.
- ID
- Selenium find element by Name
- Class Name
- Tag Name
- Link Text
- Partial Link Text
- XPath
Locator Value is the unique value using which a web element can be identified. It is the responsibility of developers and testers to make sure that web elements are uniquely identifiable using certain properties such as ID or name.
Example: WebElement loginLink = driver.findElement(By.linkText("Submit"));
FindElements Command Syntax
FindElements in Selenium command takes in By object as the parameter and returns a list of web elements. It returns an empty list if there are no elements found using the given locator strategy and locator value. Below is the syntax of FindElements command.
List
Example: List
What is XPath in Selenium?
XPath in Selenium is an XML path used for navigation through the HTML structure of the page. It is a syntax or language for finding any element on a web page using XML path expression. XPath can be used for both HTML and XML documents to find the location of any element on a webpage using HTML DOM structure.
Syntax For XPath Selenium
XPath contains the path of the element situated at the web page. Standard XPath syntax for creating XPath is: Xpath=//tagname[@attribute='value']
//: select current node
tagname: tagname of the particular node
@: select attribute
attribute: attribute name of the node
value: value of the attribute
Example of writing an XPath in Selenium:
Thanks for reading the post!