Different Types Of Locators In Selenium WebDriver

Posted by Veena Devi | November 15, 2021
Selenium Tutorial • Selenium Locators •

193616 Views | 27 Min Read

Locators In Selenium WebDriver With Examples

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Locators Tutorial.

Selenium is still the most sought-after framework when it comes to web automation testing. Though frameworks like Cypress, Puppeteer, PlayWright, etc., are playing the catch-up game, Selenium still rules the automation testing framework charts. As per my experience, every QA who wants to dabble with Selenium should have a good understanding of locators in Selenium WebDriver.

Selenium locators can be considered as the building block of any type of Selenium automation test script. The reason is simple – locators in Selenium WebDriver help you in performing the requisite interactions with the elements in the DOM.

Choosing the best-suited locators in Selenium WebDriver is one of the keys to ensuring that the tests are less flaky (or brittle) – a factor that leads to the failure of Selenium automation tests. Picture this – there is a huge test suite, and choosing inappropriate locators in Selenium WebDriver can lead to a breakdown of the entire test suite!

Avoiding such a catastrophic situation when performing Selenium automation testing is essential, making it important to choose the right locator in Selenium WebDriver for interacting with the WebElements. In this Selenium testing tutorial, I deep dive into the multiple locators in Selenium WebDriver, along with demonstrating the usage of those locators. If you are a Selenium 4 user, make sure to check out the bonus section where I have covered relative locators in Selenium 4.

What are Locators in Selenium WebDriver?

For starters, Selenium is a test automation framework that lets you automate the interactions with the WebElements on the DOM. Interactions (or actions) can be a click, type, double click, etc. For example, the Action class in Selenium provides appropriate methods to perform keyboard and mouse actions on the elements in the DOM.

However, the first operation is to identify those WebElements on the document (or page) under test. This is where locators in Selenium WebDriver come into the picture.

Locators in Selenium WebDriver provide mechanisms for identifying HTML elements on the page. Selenium supports a number of different web locators, and you have to choose the one that meets your test requirements.

Let’s consider a simple example where you need to devise a test scenario using Selenium where the email address has to be automatically entered in the text box “Your email address”.

The first task in your Selenium automation script is to identify the text box WebElement and later use the sendKeys method in Selenium for entering the email address. The identification of the WebElement (or HTML element) is made using locators in Selenium WebDriver.

Selenium WebDriver provides the findElement() and findElements() method to locate the WebElements using the appropriate web locator. Shown below is an example of how to use locators in conjunction with findElement() [or findElements()] method when using Selenium Java for web automation testing:

sendKeys method in Selenium

Also Read – What is Selenium?

unnamed (1)

How to locate WebElements in DOM

Before any interaction can be performed on the WebElements in the DOM, the first task is to locate the elements in the DOM. Follow the below-mentioned steps to locate WebElements in the DOM (Document Object Model).

1. Open the target application and click on F12 or right-click and select inspect.

2. A console window would open known Developer tools.

Developer tools

3. There is a mouse icon on the left-most side of the ‘Inspect Element’ tool. Once you hover over it, a message titled ‘Select an element in the page to inspect it’ will appear.

Click on it and navigate to the element you wish to locate. Once you click on the element, the DOM would be highlighted for that element a shown below:

Inspect Element

4. The selected row in the DOM is the context from where you want to fetch the values. For example, the highlighted DOM value is shown below:

Now you can choose the tagname, i.e., ‘a’ and link text, i.e., ‘Dashboard,’ to locate the desired element. The above technique will be used throughout my blog to demonstrate the usage of different locators in Selenium WebDriver.

Read – Selenium Locators in Protractor

Different types of Locators in Selenium WebDriver

As mentioned earlier, Selenium WebDriver provides different web locators for locating WebElements on the page. Here are the different locators in Selenium WebDriver that I will be covering in-depth in the latter part of the blog:

Below is the list of these locators of Selenium WebDriver:

Locator

Description

Syntax (in Java)

ID

Identify the WebElement using the ID attribute

driver.findElement(By.id(“IdValue”));

Name

Identify the WebElement using the Name attribute

driver.findElement(By.name(“nameValue”));

ClassName

Use the Class attribute for identifying the object

driver.findElement(By.className(“classValue”));

LinkText

Use the text in hyperlinks to locate the WebElement

driver.findElement(By.linkText(“textofLink”));

Partial LinkText

Use a part of the text in hyperlinks to locate the desired WebElement

driver.findElement(By.partialLinkText(“PartialTextofLink”));

TagName

Use the TagName to locate the desired WebElement

driver.findElement(By.tagName(“htmlTag”));

CssSelector

CSS used to create style rules in web page is leveraged to locate the desired WebElement

driver.findElement(By.cssSelector(“cssValue”));

XPath

Use XPath to locate the WebElement

driver.findElement(By.xpath(“xpathValue”));

Using locators in Selenium 4 is a treat due to the introduction of relative locators in Selenium 4. The introduction of locators like above(), below(), toLeftOf(), toRightOf(), and near() makes it easy to locate WebElements in relation to a particular WebElement.

This Selenium WebDriver Tutorial for beginners and professionals will help you learn what’s new in Selenium 4 (Features and Improvements).

How to identify elements using Locators in Selenium WebDriver

Now that I have covered the essentials of Selenium locators (including the additions in Selenium 4), let me deep-dive into each locator in Selenium WebDriver in more detail.

ID Locator In Selenium

ID locator in Selenium is the most preferred and fastest way to locate desired WebElements on the page. ID Selenium locators are unique for each element in the DOM.

Since IDs are unique for each element on the page, it is considered the fastest and safest method to locate elements. But unfortunately, developers may or may not follow this rule as browsers do allow bypassing this rule.

Specifically, in the case of a table or list, the IDs may populate incrementally or dynamically depending upon the data in the table. In such cases, testers use other locators in Selenium WebDriver to locate the desired element on the page.

One of the Selenium best practices is to leverage the capabilities offered by the ID locator in Selenium since it is the fastest locator of the entire lot. Therefore, choosing the ID locator over other locators in Selenium WebDriverwill go a long way to speed up Selenium test case execution.

Below is an example of the LambdaTest Login page showcasing how the ‘login’ field is being located via ID:

I have used the SelectorsHub tool to locate the desired WebElement using the ID locator. Below is the DOM structure of the element:

The below method is used for locating the desired element using the ID locator:

If no element in the DOM matches with the required ID, NoSuchElementException is thrown. Therefore, it is important to have a good know-how of the common exceptions in Selenium to build a more robust Selenium test suite.

This certification is for anyone who wants to stay ahead among professionals who are growing their career in Selenium automation testing.

Here’s a short glimpse of the Selenium 101 certification from LambdaTest:

Name Locator In Selenium

An element can be defined via multiple attributes, one such attribute is Name. Name locator in Selenium WebDriver can also be used to locate elements like an ID locator.

Unlike ID locators, which are unique for a page, the Name locator may or may not have a unique value. If there are WebElements with the same name, the locator selects the first element with that Name on the page.

In case no such name matches with the defined attribute value, NoSuchElementException is raised.

To demonstrate the usage of the Name locator in Selenium WebDriver, we identify the same WebELement that was earlier located using the ID locator.

Here is how the desired WebElement was located using the Name locator in Selenium:

‘Link Text’ Locator In Selenium

Elements can be located via link text that is present in the hyperlinks. For example, the first link would be selected in a scenario where there are multiple links of the same text.

However, this Identifier strategy can only be used for elements that have an anchor(a) tag.

Below is an example of Lambdatest homepage showcasing the selection of the ‘Automation’ link that is available on the header. The DOM below shows the highlighted element:

Locator In Selenium

Below is the DOM structure of the same:

Here is how the desired WebElement was located using the linkText locator in Selenium:

Partial Link Text Locator In Selenium

There is a provision to locate a WebELement using Partial Link Text akin to the normal Link Text locator in Selenium. Locating WebElements using partial link text is preferred when the link text is too long.

Here, the partial text helps identify a unique element and use it to perform further actions on it. Sometimes, using this can also be to locate multiple links on a page with a common partial text.

Read – How to find HTML elements in Cypress

Below is a snapshot of the LambdaTest DOM highlighting the element with the link name as ‘Start testing.’ Instead of using the complete link text, I use the partial link text locator to locate the element using the ‘testing’ link text.

Link Text Locator In Selenium

Here is the DOM structure of the element:

Here is how the desired WebElement was located using the partial link text locator in Selenium:

The syntax for locating element by partial link text is:

TagName Link Text Locator In Selenium

As the name specifies, this CSS locator in Selenium WebDriver is used to identify elements using Tag names like div, table, h1, etc.

The TagName locator is commonly used to identify all the links on a page and identify broken links in Selenium.

broken links in Selenium

Here is the syntax of locating all the links on the LambdaTest homepage:

ClassName Locator In Selenium

Class Name locator is used for locating WebElements that are defined using the class attribute. Shown below is the DOM snapshot of the LambdaTest login page.

ClassName Locator in In Selenium

For locating the ‘login’ element via the ClassName locator in Selenium, we use the class attribute in the following DOM structure:

Here is how the desired WebElement was located using the ClassName locator in Selenium:

XPath Locator In Selenium

XPath locator in Selenium helps in locating elements on the web page using XML expressions. The basic syntax used for using XPath as a CSS locator in Selenium WebDriver is shown below:

Here, TagName in Selenium signifies the tag in the DOM structure that you are targeting to locate the desired WebElement. TagName can be input tag, anchor tag, etc.

Attributes are defined via the prefix ‘@’ and their corresponding value. Thus, attributes like Name, ID, Class, etc., can be used along with TagName.

XPath in Selenium can be used in multiple ways, as shown below:

  • Standard XPath

As the name indicates, this is the most basic (or standard) way of writing an XPath. To demonstrate the usage of a standard XPath locator in Selenium, let’s locate the email element on the LambdaTest homepage.

Standard XPath

Below is the DOM structure of the element:

The standard XPath of the desired WebElement is //input[@name= ’email’]. Here is how the XPath is used with the findElement() method to locate the element.

  • XPath Contains

XPath similarly contains works like CSS selector ‘contains.’ It is extensively used on WebElements whose value is changing dynamically.

Consider an example where the value of the login changes after appending the login text. Here, XPath contains will be super-helpful in locating the desired WebElement.

Syntax:

Below is the DOM structure of the element:

Here is how the desired WebElement was located using the ‘XPath contains’ locator in Selenium:

XPath using ‘AND’ & ‘OR’

The ‘AND’ & ‘OR’ operators in the XPath selector in Selenium are used when locating a WebElement based on certain condition sets. In the case of ‘AND,’ both the conditions should be True. On the other hand, either of the two conditions can be true for ‘OR’ in operator XPath.

Syntax of OR operator in XPath:

Syntax of AND operator in XPath:

Let’s locate the email login element on the LambdaTest homepage using the ‘AND’ & ‘OR’ operators.

LambdaTest homepage

Below is the DOM structure of the element:

Here is how we used the OR operator with XPath locator in Selenium:

Here is how we used the AND operator with XPath locator in Selenium:

starts-with() method in XPath

The starts-with() method in XPath offers functionalities that are similar to the CSS Selector in Selenium. It helps in locating elements that start with a specified attribute value. The starts-with() method in XPath is majorly used for locating WebElements whose value changes on the refresh of a page.

Syntax:

Shown below is the DOM structure for locating the Password field on the LambdaTest signup page:

method in XPath

Below is the DOM structure of the element:

Here is how we locate the Password element using the starts-with() method with XPath in Selenium:

XPath Text

Text in the XPath locator in Selenium helps in locating WebElements via XPath using exact text match. It can be used when elements have to be located by looking into the tags containing certain text.

Syntax:

To demonstrate XPath text usage, we locate the ‘FREE SIGN UP’ button on the LambdaTest registration page.

LambdaTest registration page

Here is the DOM structure of the required WebElement:

Here is how we locate the ‘FREE SIGN UP’ button element using the XPath text:

Both CSS Selector and XPath are useful when running complex Selenium test automation scenarios. Though I use XPath extensively, the choice between XPath and CSS Selector purely depends on the scenario complexity and your convenience in locating WebElements using the corresponding locator.

When choosing, always look into the maintainability aspects of the locators, as that can make your job easier! Been there, done that by choosing the relevant locators in Selenium WebDriver when strategizing the Selenium automation testing strategy 🙂

Read – ClassName locator in Selenium Java

CSS Selector Locator In Selenium

CSS (Cascading Style Sheets) is used to style web pages. At the same time, CSS is also one of the widely-used ways to locate WebElements in the DOM.

CSS Selector in Selenium should be opted if you cannot locate an element using ID or Name locators. It can be chosen over the XPath locator.

Since multiple debates go around the corner for both of them, their usages for me depend on the complexity of the scenario. However, most people prefer using CSS selectors since those are faster than XPath.

Here are the different ways in which QA engineers can make use of CSS Selectors in Selenium:

Tag and ID in CSS Selector

To locate elements by Tag and ID, you have to use the following components:

  • Html tag: It provides the tag we wish to locate (e.g. input tag).
  • #: It is used to represent the ID attribute. Keep in mind that when you wish to locate an element via ID through a CSS selector, it must have a hash sign on the same. For other attributes, we need not use the hash sig
  • Value of the ID attribute: This represents the value of the ID we are using to locate the element.

Syntax

Example

Below is the DOM part indicating the login field of Makemytrip.com

Here is how you can locate the required WebElement using the CSS Selector:

Tag and Class in CSS Selector

Apart from the syntax (or format) difference, the said locator is pretty much identical to the ID locator. A dot (.) is used when denoting the class attribute value rather than hash (#) in the case of class.

Syntax

Example

Here is the DOM snapshot and the corresponding command to access the required WebElement using CSS Selector in Selenium:

CSS Selector in Selenium

This is how the Submit button is located using CSS Selector in Selenium

Tag and Attribute

The element can be located via tag name, and the corresponding attribute is defined using its value. In case multiple elements have the same tag and attribute, the first one will be selected.

Syntax

Example

Here is the DOM structure:

Here is how the WebElement – ‘phone’ can be located using the CSS Selector in Selenium:

Tag, Class, and Attribute

This locator is used with the class name and other attribute values.

Syntax

Let’s locate the ‘Free Sign Up’ button on the LamdaTest Signup page:

LamdaTest Signup page

Here is the DOM structure of the ‘FREE SIGN UP’ WebElement:

Here is how you can locate the ‘FREE SIGN UP’ button the LambdaTest signup page:

This combination can also be implied on ID. The only difference is to use a hash (#) rather than a dot (.) when using an ID attribute and defining its ID value in place of the Class value.

Wild (*, ^ and $) in CSS for classes

Selenium CSS selector in Selenium helps in matching multiple strings through the use of multiple patterns like ^, $, *. Wildcard selectors in CSS are used for selecting multiple elements simultaneously.

Here are the ways in which wild cards can be effectively used with the CSS Selector in Selenium:

a. Starts-With in CSS Selector

The Starts-With helps locate elements when we try to match elements with a string that starts with a designated value.

Syntax

Example

Here is the DOM structure for locating the WebElement:

Here how the CSS [attribute^=value] Selector is used for locating the desired WebElement:

b. Ends-With in CSS Selector

This helps locate elements when we try to match elements with a string that ends with a designated value.

Syntax

Example

Here is the DOM structure of the element:

Here is how Ends-With in CSS Selector is used for locating the required WebElement:

c. Contains in CSS Selector

This helps locate elements when we try to match elements with a string containing a designated value.

Syntax

Example

Here is the DOM structure to locate the element:

Here is how Contains in CSS Selector is used for locating the required WebElement:

d. Child Elements in CSS Selector

With the use of child elements, we can locate elements inside other elements. Child Elements in CSS Selector is particularly useful when trying to access data from a table, list of details, and more.

Example

For demonstrating the usage of Child Elements in CSS Selector, we locate a Child Element with reference to a particular element. The URL under test is the LambdaTest Blog link in the menu on the LambdaTest home page.

Child Elements in CSS Selector

Here is the DOM structure to locate the element:

In order to locate element, the following syntax would be used:

Here is how you can get the blog link from the page:

Similarly in order to access responsive we can use, last-child reference as below:

Blog on CSS Selectors in Selenium Automation Scripts is a good resource to further drill down into the CSS Selectors in Selenium.

One of the major features of Selenium 4 is the introduction of relative locators. Relative locators in Selenium 4 help you search for WebElements in relation to the other elements.

For example, using toLeftOf Selenium 4 relative locator, WebElements to the left of a certain element can be easily located. This results in a few findElement calls primarily used for locating elements on the page.

The difference between Selenium 3 and Selenium 4 is a good starting point to know the immense potential offered by the Selenium 4 framework. Here is a short gist of relative locators in Selenium 4:

Selenium 4 Locator

Description

Syntax (in Java)

above

The desired WebElement is above the specified element

driver.findElement(with(By.tagName(“TagName”))

.above(ElementName));

below

The desired WebElement is below the specified element

driver.findElement(with(By.tagName(“TagName”))

.below(ElementName));

toLeftOf

The desired WebElement is located to the left of a particular element

driver.findElement(with(By.tagName(“TagName”))

.toLeftOf(ElementName));

toRightOf

The desired WebElement is located to the right of a particular element

driver.findElement(with(By.tagName(“TagName”))

.toRightOf(ElementName));

near

The desired WebElement (or item) is located no more than 50 pixels from the specified element

driver.findElement(with(By.tagName(“TagName”)).near(ElementName));

Selenium 4 Learning Hub is the go-to resource to check what’s new in the Selenium 4 framework.

To demonstrate the usage of relative locators in Selenium 4, we locate the WebElements on the LambdaTest Certifications Page.

LambdaTest Certifications

The first unique WebElement on the page is located using the following method:

Here is how below relative locator in Selenium 4 is used to locate the element below the Element we searched earlier:

The next set of WebElements on the page are identified using the above, below, toLeftOf, and toRightOf locators in Selenium 4:

Here is the code snippet that showcases the usage of relative locators in Selenium 4:

Shown below is the console output:

fetched via Below: Selenium C# 101
fetch via ToTheRight: Selenium Java 101
fetch via above: Selenium Python 101
fetched via toLeftOf: Cypress 101

You can also use a combination of relative locators to locate the desired WebElement.

This code identifies an element, which is below a given WebElement and to the right of the newly searched element.

Best practices for using Locators in Selenium WebDriver

The main challenge in writing automation scripts lies in locating the right identifier for the target element. Following certain best practices will ensure that the team uses strategy efficiently to locate elements used in automation scripts.

Following are some of the best practices for using locators:

  • Use a unique ID for element identification
    The first and main reason to use a unique ID is that it makes it simpler to identify a particular element. If you have two elements with the same ID, it becomes difficult to determine which element you want to use in your scripts. This may lead to issues such as selecting an incorrect element or a non-existent one. To avoid this, always assign a unique ID for each element you wish to utilize in your web application to avoid this.
  • Avoid using Ids that change locations
    Selenium WebDriver locators depend on IDs because they match the ID attribute assigned by browsers, which is used as identifiers for each HTML tag on your page. The value of these IDs remains static as long as the browser window remains open. However, if you close and reopen the browser, these values change their position due to the fact that they now identify different objects on the page.

    For example, if the locator is dependent on a single entity like class, name, id, etc., which, if changed, can be repaired but complex locators like By.XPath(“//div[@class=”class-form_6180″]/div[5]/h3”) may lead to frequent breakage if any of the div or the class name changes.

    So, while using locators in Selenium WebDriver, do not locate elements that depend on auto-generated values. This is one of the key rules that one needs to keep in mind about locators in Selenium WebDriver for writing better automation code.

  • Keep your Locators short
    Your locator should always identify the exact target element you want to click or locate and not other elements that are present on the same page. The benefit of this is that you’re reducing the chance of your script breaking because the number of elements on a page has changed (and thus, where they appear in the HTML code). Also, if your locator is short, it’s easier to see if it’s affecting more than one element.

    Secondly, if you are trying to look out for multiple matches (using ‘findElements’), ensure it matches all the desired elements you are looking out for.

  • Avoid elements that depend on auto-generated values
    If you are using locators such as ID, CSS, and XPath, Selenium WebDriver provides a way to navigate to elements through the browser’s address bar. This is accomplished by using the locateElement() or locateElementBy*() methods. You can navigate to any element on the page by using the browser’s address bar and its locator parameters and values and this method. However, if you use IDs (e.g., “id=”tooltip””) as locators, it might not work quite as you expect. This is because IDs are auto-generated and do not always change when we expect them to.

    As a best practice, the first thing we should do is always use locators such as CSS and XPath instead of IDs as they never change their value. The second thing we should do is to watch those values after each run. So, if we want to locate an element with an ID of tooltip using the browser’s address bar, we should run and watch the values of those IDs to identify if they are auto-generated or not.

  • Don’t use XPath or CSS Selector provided by the Dev Tools
    Choosing locators in Selenium is an important step, especially when you are new to it. There are many tips and tricks available on the web regarding this topic. But most of them suggest using XPath or CSS selectors provided by the browser’s dev tools.

    However, if you use XPath or CSS Selectors provided by the browser’s dev tools, your tests will not work if the source code is changed. To have stable tests, you should use locators that are independent of HTML structure.

Conclusion

With this, we come to the end of the tutorial on Selenium Locators. In this tutorial on locators in Selenium WebDriver, we first looked at different ways of locating WebElements in DOM. We also looked at different types of locators and relative locators used in Selenium and ways to locate elements using the id, name, class, and attribute selectors.

Selenium locators can be used as a handy resource when you are performing Selenium automation testing. When it comes to Selenium automation testing, Selenium testing tools like LambdaTest offer the broadest set of cloud-based testing capabilities. With a single Selenium Grid node, you can access 2000+ browsers and operating systems for cross browser testing, and more.

Now that you have learned how to use locators and relative locators in Selenium WebDriver, you should be able to work with locators effectively. I hope that this tutorial has helped you learn everything there is to know about using locators in the Selenium WebDriver.

Frequently Asked Questions

What are the 8 locators in Selenium?

Selenium supports eight different locators for finding elements: id, name, className, tagName, linkText, partialLinkText, CSS selector and XPath

Which is the best locator in Selenium WebDriver?

IDs are the most reliable locator option in web design in that they are guaranteed to be unique on the page by W3C standards. You can’t have two elements with the same ID within one page.

Is XPath a locator in Selenium?

XPath is used to locate elements on a web page using the HTML Document Object Model (DOM) structure.

What are locators explain its types?

Locators are used to identify elements on a Webpage. A locator can either be a basic attribute value, be an XPath query, identify an element from the DOM or CSS-based Locator or HTML5 based locator. We can use locators to find elements of a web page accurately.
Following are the types of locators supported by Selenium Webdriver:

  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath
  • CSS Selector

How many locators are there?

Selenium WebDriver supports locating elements by ID, Name, Link Text, Partial Link Text, Class, CSS Selector, and XPath.

What do you mean by locators in Selenium?

Locators are commands that tell Selenium IDE where to find elements. They are used when identifying the correct GUI elements.

Why do we need locators in Selenium?

Locators provide a way to access an HTML element from a web page. In Selenium, we can use locators to perform actions on the text boxes, links, checkboxes, and other web elements. They are necessary for us to explore and manipulate a website by its components.

What are the criteria to use the locators?

Rules for Choosing the Best Locators

  • Must match the desired element
  • Must not match any other element
  • Avoid information that can change
  • Depend on the minimal required information

Written by Sadhvi Singh

Sadhvi Singh is a QA Manager. In 7 years of her professional journey, she has worked on multiple domains and testing techniques like Automation testing, Database testing, API testing, Manual testing, and Security testing. With multiple tools exposure added to her experience, she has skilled herself further through her two major accolades at International level through ISTQB with foundation and advanced levels. She has a technical blog named as qavibes.blogspot.com where she caters to all the challenges offered in the day to day journey of the quality assurance aspirants. In her spare time, she also works as a technical trainer and mentor to many budding QA professionals.

Related Articles

cross-browser-testing-in-selenium

Cross Browser Testing In Selenium [Tutorial]

193774 Views | 16 Min Min Read

Selenium testing myths

Debunking The Top 8 Selenium Testing Myths

71865 Views | 10 Min Min Read

Leave a Reply

Your email address will not be published. Required fields are marked *