Locators in Selenium | Types, Example
In this tutorial, we will know about element locators in Selenium with the help of examples.
Locators help us to find the location of elements on the web page using WebDriver API.
When we are working with WebDriver on a web application, we need to understand the location of elements on the web page.
All the methods present in the Selenium WebDriver search the element first to perform actions on the web application such as clicking, selecting, typing, etc.
Locating an element is one of the most important tasks in selenium tests but there is no fixed strategy that you can follow to identify an element (object) uniquely on the web page. It totally depends on the user’s ideas and their comfort level in locating web elements.
To recognize the element (Object) uniquely on the web page, Selenium gives us some locator strategies. So, let’s start with what is locators in Selenium?
What is Locator in Selenium
Locator in selenium is like an address that is used to identify the web element uniquely on the web page.
In other words, it is a technique to recognize an object on the web page uniquely by using different identification methods.
The main objective of using element locators is to identify the element or object on the webpage accurately.
Selenium WebDriver uses element locators to interact with elements present in a web page. Once the element is recognized, the action can be performed on it.
All elements that are present on a web page are called Web elements which can be located using any kind of locator type.
For example, you can see the view of HTML code written for the web element “Username” on the Facebook login page in the below figure.
Selenium WebDriver uses the “findElement(By.locator())” method to find a web element on web page. This method search for an element based on the criteria given to it. If a matching element is found, it will return a web element object.
[adinserter block=”5″]
If the method is not able to find any matching element with search criteria then it will throw NoSuchElementException exception.
Selenium also provides to use “findElements(By.locator())” method to find multiple elements on the web page. This method will search and return a list of WebElement objects that match with the search criteria.
Types of Locators in Selenium WebDriver
Selenium WebDriver uses 8 types of locators to locate an element on the web page. They are as follows:
- ID
- Name
- ClassName
- TagName
- LinkText
- PartialText
- CSS
- Xpath
Let’s understand all eight types of locators with examples one by one.
ID locator
ID locator is the safest and fastest locator to find the location of an element based on the value of “ID” attribute on a web page. It is the most efficient and preferred way to find a web element.
Since ID is unique for each element on the web page so it can be easily identified. It is always the first choice for testers. It is mostly an account number, college name, username, password, or sign in button that will be unique.
The general syntax to use id locator is as follows:
WebElement element = driver.findElement(By.locatorType("Attribute value"));
where,
driver ➨ Object reference variable of the WebDriver object.
WebElement ➨ Return type of the findElement() method.
element ➨ Variable used to store the returning web element.
By ➨ By is a class that extends java.lang.Object. It provides a mechanism that is used to locate elements within a document.
[adinserter block=”2″]
For example:
< input id="college name" class="required" type="text"/> WebElement element = driver.findElement(By.id("college name")); // The above code can also be written directly as driver.findElement(By.id("college name")); // Here. college name is attribute value.
Unfortunately, you will get in many cases where an element does not have a unique id. In this case, you will have to choose an alternative locator to find objects on the web page.
Name Locator
Name locator is the second safest and fastest locator to locate an element based on the value of “name” attribute on the web page. The name cannot be unique for each element at all times.
If there are multiple elements with the same name on a web page then Selenium will always perform the action on the first matching element.
Username and Password fields are examples that can be identified with “name” attribute. The general syntax to use name locator is as follows:
WebElement element = driver.findElement(By.name("Attribute value")); For example: < input name="firstname" class="required" type="text"/> WebElement register = driver.findElement(By.name("firstname")); // firstname is attribute value. Other examples are: WebElement emailElement = driver.findElement(By.name("EmailID")); WebElement submitElement = driver.findElement(By.name("Submit"));
ClassName Locator
Class Name locator finds an element based on the value of “class” attribute on the web page. The general syntax is like this:
WebElement element = driver.findElement(By.className("Attribute value")); For example: WebElement paper = driver.findElement(By.className("sample")); // Here, the attribute value is sample and paper is variable used to store returning value.
TagName Locator
TagName locator is used to finding an element from the group elements like checkboxes, drop-downs, etc. It locates an element by its tag name.
WebElement element = driver.findElement(By.tagName("Attribute value")); For example: WebElement element = driver.findElement(By.tagName("div")); // Here, div is the attribute value of tagName.
LinkText Locator
This locator finds an element by the link text. If there is one unique element on the web page, you can easily find an element with the link text.
For example, My Account link can be identified using link text on the web page.
But if there are multiple links with the same link text such as repeated header and footer on the web page. In such cases, selenium will select the first matching element with the link.
The general syntax to identify an element by link text is as follows:
WebElement linktext = driver.findElement(By.linkText("Atrribute value")); For example: <a href="https://www.seleniumhq.org>Download</a> // Here, Download is link text. WebElement download = driver.findElement(By.linkText("Download"));
Partial LinkText Locator
This locator locates an element by a partial match of its link text and then performs actions on it. It works in the same way as the link text. The general syntax is given below:
WebElement partialLinktext = driver.findElement(By.partialLinkText("Attribute value")); For example: < a href="https://www.seleniumhq.org">Download Selenium Server</a> WebElement download = driver.findElement(By.partialLinkText("Download"));
CSS Selector Locator
This locator finds an element by the CSS selector on the web page. CSS selector makes the execution of test scripts faster as compared to the XPath locator.
It is the best way to find an element on the web page. The CSS stands for Cascading Style Sheets.
WebElement element = driver.findElement(By.cssSelector("Attribute value")); For example: WebElement element=driver.findElement(By.cssSelector("input#email"));
You can check for W3C CSS Locators here.
XPath Locator
XPath stands for XML (Extensible Markup Language) Path language. It is a query language that is used to search and select the node in an XML document. All the major web browsers support XPath.
Selenium web driver supports XPath to find the location of any element on a web page using XML path expression. XPath produces a reliable locator but the performance of XPath is slower than CSS selector.
The path of the element at the webpage is selected by XML path syntax. The standard syntax for creating XPath is shown below:
XPath = //tagname[@attribute = 'value']
where,
// ➨ It selects the current node.
Tagname ➨ It is the name of the tag of a particular node. For example, input.
@ ➨ It selects attributes like id, name, className, etc.
Attribute ➨ Name of the node. For example, type, class, name, id, etc.
Value ➨ value of the attribute.
For example:
XPath = //input[@id='user-message'] WebElement username = driver.findElement(By.xpath("//input[@id='user-message']"));
Types of XPath in Selenium
There are two types of XPath in Selenium. They are:
- Absolute XPath
- Relative XPath
Absolute Xpath
➲ It is the easiest way to find the element but if any changes are made in the path of the element then this XPath gets failed. So, This is the main disadvantage of absolute XPath.
➲ It begins with a single forward slash (/) which selects the element from the root HTML node. The example of an absolute XPath expression of the element is given below:
Absolute XPath = /html/body/div/div/form/input WebElement userName = driver.findElement(By.xapth("/html/body/div/div/form/input"));
Relative XPath
➲ It starts from the double forward slash(//) and selects the element from anywhere on the webpage.
➲ It is the best practice to find an element through a relative XPath and helps us to reduce the chance of “element not found exception”.
➲ With a relative XPath, we can locate an element directly irrespective of its location in the DOM. The example of relative XPath is given below:
Relative XPath = //input[@class='social-media'] WebElement username = driver.findElement(By.xpath("//input[@class='social-media']"));
Hope that this tutorial has covered almost all the important points related to locators in Selenium with examples. Keep in mind the following key points related to XPath locators.
Key Points to Remember:
1. The priority of locator type in this order: id > name > CSS> XPath.
2. DOM (Document Object Model) allows element identification by using HTML tag name associated with element.
3. It is important to use an appropriate locator to identify an element on the page that must be unique.
4. If an element is associated with a link, use linkText or partialLinkText to identify element.
Thanks for reading!!!