Types of Locators to identify the WebElements

A web page consists of set of different web elements. We need to know what are the different elements on a web page and then how to locate the web elements.

Here are some common web elements we encounter most of the time while automating the web page.
Text box
Drop-down List
Checkbox
Radio button
Hyperlink
TextArea
Image
Button
Window

An element locator is simply a method for finding an element on the web page.
We can use the following locators based on priority to identify the elements on the web page.
– Locating By Id
– Locating By Name
– Locating By Class
– Locating Hyperlinks by LinkText
– Locating By Xpath
– Locating By CSS

Steps to find the element locator for the web element:
-> Search for the locator which will find the element by ID or proceed to the next step.
-> Search for the locator which will find the element by Name or proceed to the next step.
-> Search for the locator which will find the element by Class or proceed to the next step.
-> Search for the locator which will find the element by LinkText or proceed to the next step.
-> Search for the locator which will find the element by XPath or proceed to the next step.
-> Search for the locator which will find the element by CSS or proceed to the next step.

While following the above steps to locate elements, a question may come to our mind that why there are so many types of locators instead of any one to identify the elements.

Element Locator is a way of finding the HTML element on the web page. Every HTML element on the page we are testing with Selenium will have a unique Name or ID that we can always refer to. But, usually we are doing black box testing and have no access to the developer’s code and there is difficulty in finding the correct elements due to absence of unique identifier like Name or ID. Also, there are some web applications which recreates the element ID each time dynamically when the application is run. In this case, it is very difficult to handle if we depend on only one type of locator.

Some basic syntax for different locators:
1. By ID:
driver.findElement(By.id(“element id”))

2. By NAME:
driver.findElement(By.name(“element name”))

3. By CLASS:
driver.findElement(By.className(“element class”))

4. By Link:
driver.findElement(By.link(“link text”))

5. By XPath:
driver.findElement(By.xpath(“xpath expression”))

6. By CSS Selector:
driver.findElement(By.cssSelector(“css selector”))

These locators can be identified by using Firebug and Firepath plugins in Firefox Browser