Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud
  • Home
  • /
  • Blog
  • /
  • Locators In Selenium WebDriver With Examples
Selenium TutorialSelenium LocatorsTutorial

Different Types of Locators in Selenium WebDriver

Learn different types of locators in Selenium WebDriver and how to use them for Selenium automation testing

Author

Faisal Khatri

February 17, 2026

When writing automated tests with Selenium WebDriver, the first step is locating the WebElements using the browser developer tools window. To achieve this, different types of locators in Selenium WebDriver, like ID, Name, TagName, ClassName, XPath, CSS Selector, etc., can interact with those respective WebElements.

Selenium locators are like the building block of a test script that helps testers interact with the elements in the Document Object Model (DOM). Choosing the best-suited locators in Selenium WebDriver is one of the keys to ensuring that the tests are less flaky (or brittle).

In this tutorial, we deep dive into the multiple locators in Selenium WebDriver, along with demonstrating the usage of those locators. If you are preparing for an interview you can learn more through Selenium interview questions.

What are Locators in Selenium WebDriver?

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.

Web Element Locators Explained By Louise J Gibbs

By Louise J Gibbs

Download Image

However, the first operation is identifying 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 several web locators, and you have to choose the one that meets your test requirements.

Let’s consider a simple example from the TestMu AI Selenium Playground website’s Input Form Demo page. You need to devise a test scenario using Selenium and enter the email value in the Email text box field.

lenium and enter the email value in the Email text box

The first task in your Selenium automation script is to identify the web element of the Email field and later use the sendKeys() method in Selenium to enter the email address. The web element (or HTML element) is identified using locators in Selenium WebDriver.

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

findElement() and findElements(

For more information on locators, please refer to this Selenium Locators Cheat Sheet.

What are Locators Used for?

The primary usage of a locator is to locate a web element on the web page. The locators can then be used in Selenium WebDriver test scripts to interact with the web element and perform different actions such as clicking, entering keys, opening a dropdown, ticking a checkbox, etc.

Using the combination of these actions, the appropriate functionality of the web pages can be tested. Locators help us verify the presence of the web element and its visibility and check the state of the web element, whether it is enabled or disabled.

Locators are an essential part of the test scripts, without which the automated testing can not perform the desired output. If the right locators are not used, it may result in failures and flaky tests. Understanding the locator strategies is necessary as it can help save time and effort in writing the automated tests.

...

Advantages of Locators in Selenium WebDriver

There are multiple advantages of locators in Selenium WebDriver, some of which are listed below:

  • Once the web element is located on the web page, it can run the same tests on different browsers installed on various platforms. Thus, helping to perform the cross browser testing efficiently.
  • A web element can be located using different locator strategies in Selenium WebDriver. If the web element has an ID and name, it can be located using its ID, Name, XPath, or CSS Selector. Similarly, the respective tagName or the className can locate the same WebElement. Hence, there is a lesser chance that the tester might face difficulty locating a WebElement.
  • Once a WebElement is located, it can be reused in the tests, thus saving the tester effort and time while writing the test script. This also helps remove redundancy and create robust test scripts.
  • CSS Selectors can locate the WebElement in multiple ways, such as using ID and tagName, className, ID, other attributes, etc. Similarly, XPaths could also locate the WebElements using relative or absolute path. ID is the fastest of all locators; however, it requires that the WebElement should contain the ID attribute. The same applies to the Name locator as well.

The point here is that every locator serves different needs, so if ID and Name are not available in the WebElement, CSS Selector or XPath could be used to locate the WebElement, thus making the way out for testers so they don’t get blocked.

How to Locate WebElements in DOM?

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

  • Open the website and click on F12, or right-click and select Inspect.
  • Open the website
  • A Chrome Developer Tools console will launch.
  • Chrome Developer Tools console
  • There is a mouse icon on the leftmost side of the Developer Tools console. 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 will be highlighted for that element, as shown below.

  • DOM will be highlighted for that element
  • 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.
<input type="email" class="w-full border border-gray-90 text-size-14 rounded mt-10 px-10 py-5" id="inputEmail4" name="email" placeholder="Email" required="">

Now, you can choose the id, i.e., inputEmail4, to locate the desired Email text box element. The above technique will be used throughout this blog to demonstrate the usage of different locators in Selenium WebDriver.

Different Types of Locators in Selenium WebDriver

Below is the list of these locators of Selenium WebDriver:

  • ID
  • Name
  • ClassName
  • LinkText
  • Partial LinkText
  • TagName
  • CSS Selector
  • XPath

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

LocatorsDescriptionSyntax (in Java)
idIdentify the WebElement using the ID attribute.driver.findElement(By.id(“IdValue”));
nameIdentify the WebElement using the Name attribute.driver.findElement(By.name(“nameValue”));
classNameUse the Class attribute for identifying the object.driver.findElement(By.className(“classValue”));
linkTextUse the text in hyperlinks to locate the WebElement.driver.findElement(By.linkText(“textofLink”));
partialLinkTextUse a part of the text in hyperlinks to locate the WebElement.driver.findElement(By.partialLinkText(“PartialTextofLink”));
tagNameUse the tagName to locate the desired WebElement.driver.findElement(By.tagName(“htmlTag”));
cssSelectorCSS used to create style rules in the web page is leveraged to locate the desired WebElement.driver.findElement(By.cssSelector(“cssValue”));
xpathUse 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.

We carried out a poll on LinkedIn to get insights into the testing community’s preferences, particularly regarding locators in Selenium WebDriver. We asked, ‘What is your favorite element locator in Selenium WebDriver for test automation?’ The responses showed a clear preference for XPath among professionals. This finding emphasizes the important role of XPath as a locator in Selenium WebDriver for test automation.

WebDriver for test automation

Source

Identify WebElements Using Locators in Selenium WebDriver

Now that you know 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 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. 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 on 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 WebDriver will go a long way to speed up Selenium test case execution.

Below is an example of the TestMu AI eCommerce Playground showcasing how the E-Mail Address field can be located using the id locator:

Chrome Developer Tools menu

I have used the Chrome Developer Tools menu to locate the WebElement using the id locator. Below is the DOM structure of the element:

<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control">

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

driver.findElement(By.id("input-email"))

If no DOM element matches 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.

Name Locator in Selenium

An element can be defined via multiple attributes, one such attribute is Name. A Name locator in Selenium WebDriver can also 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 will identify the same E-Mail Address fields that were located using the ID locator.

E-Mail Address fields that
<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control">

Here is how the desired WebElement can be located using the name locator in Selenium:

driver.findElement(By.name("email"));

LinkText Locator in Selenium

Elements can be located by LinkText, which is present in the hyperlinks. For example, the first link would be selected in a scenario with multiple links of the same text.

However, this identifier strategy can only be used for elements with an anchor( < a > ) tag.

Below is an example of the TestMu AI Selenium Playground website showcasing the selection of the Ajax Form Submit link that is available on the home page. The DOM below shows the highlighted element:

LambdaTest Selenium Playground

Below is the DOM structure of the same:

<a href="https://www.lambdatest.com/selenium-playground/ajax-form-submit-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Ajax Form Submit</a>

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

driver.findElement(By.linkText("Ajax Form Submit"));

Partial LinkText Locator in Selenium

There is a provision to locate a WebElement using Partial LinkText akin to the normal LinkText locator in Selenium. Locating WebElements using Partial LinkText is preferred when the link text is too long.

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

Below is a snapshot of the TestMu AI DOM highlighting the element with the link name as Auto Healing. Instead of using the complete link text, I used the partial link text locator to locate the element using the Healing link text.

LambdaTest DOM highlighting

Here is the DOM structure of the element:

<href="https://www.lambdatest.com/selenium-playground/auto-healing" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Auto Healing</a>

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

The syntax for locating elements by partialLinkText is:

driver.findElement(By.partialLinkText ("Healing"));

For more information on Link Text and Partial LinkText locators, we recommend you check this article to find elements with linkText and partialLinkText in Selenium.

TagName 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 in Selenium is commonly used to identify all the links on a page and identify broken links in Selenium. It is also used to get the header or the title of the web pages.

broken links in Selenium

Here is the syntax for locating all the links on the TestMu AI Selenium Playground homepage. Notice here that the findElements method is used. It will return a list of all the WebElements with the tagNamea” that normally holds the links:

driver.findElements(By.tagName("a"));

Watch this video to learn the Actions class in Selenium and how to use it.

ClassName Locator in Selenium

ClassName locator is used for locating WebElements defined using the class attribute. Below is the DOM snapshot of the Ajax Form Submit page that is available on the TestMu AI Selenium Playground website.

Ajax Form Submi

For locating the WebElement of the Submit button via the className locator in Selenium, we use the class attribute in the following DOM structure:

<input type="button" class="btn btn-dark selenium_btn bg-black text-white hover:bg-lambda-900 py-5 px-10 rounded" name="btn-submit" id="btn-submit" value="submit">

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

driver.findElement(By.className("btn-dark"));

XPath Locator in Selenium

XPath locator in Selenium helps locate 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:

XPath: //tagName[@attribute = 'value']

Here, tagName in Selenium signifies the tag in the DOM structure you are targeting to locate the desired WebElement. tagName can be an 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 WebElement of the E-Mail Address field on the TestMu AI eCommerce Playground website.
Standard XPath

Below is the DOM structure of the element:

<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control">

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.

driver.findElement(By.xpath("//*[@id="input-email"]"));
  • XPath Contains: XPath similarly contains works like CSS Selector contains. It is extensively used on WebElements, whose value changes 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:

  • //tagname[contains(@attribute, 'partial value of attribute')]
    

    Below is the DOM structure of the element:

    <input type="text" placeholder="Full Name*" name="name" value="" class="form-control sign-up-input-2 ">
    

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

    driver.findElement(By.xpath("//input[contains(@class, 'form-control')]"))
    

XPath Using AND and OR

The AND, 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 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:

//input[@id='login_1' OR @name='login']

Syntax of AND operator in XPath:

//input[@id='login_1' AND @name='login']

Let’s locate the email address field’s element on the TestMu AI eCommerce Playground Account Login page using the AND and OR operators.

Account Login page

Below is the DOM structure of the element:

<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control">

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

driver.findElement(By.xpath("//input[@id="input-email" or @name="email"]"));

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

driver.findElement(By.xpath(""//input[@id="input-email" AND @name="email"]"));

starts-with() Method in XPath

The starts-with() method in XPath offers functionalities 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:

//tagname[starts-with(@attribute,'starting name of the attribute value')]

Shown below is the DOM structure for locating the Password field on the TestMu AI eCommerce Playground website’s Account Login page:

eCommerce Playground website’s Account Login

Below is the DOM structure of the element:

<input type="password" name="password" value="" placeholder="Password" id="input-password" class="form-control">

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

driver.findElement(By.xpath("//input[starts-with(@name,'pass')]"));

XPath Text

Text in the XPath locator in Selenium helps locate 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:

//div[text()='Logged In']

To demonstrate XPath text usage, we will locate the Submit button on the Auto Healing page on the TestMu AI Selenium Playground website.

LambdaTest Selenium Playground website

Here is the DOM structure of the required WebElement:

<button type="submit" class="bg-black hover:bg-transparent hover:text-black border border-black text-white rounded focus:outline-none selenium_btn py-5 px-10 rounded mt-20 w-120">Submit&lt;/button>

Here is how we locate the Submit button element using the xpath text:

driver.findElement(By.xpath("//button[text()='Submit']"));

Both CSS Selector and XPath are helpful when running complex Selenium test automation scenarios. 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!

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.

The CSS Selector in Selenium should be chosen 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 usage may 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. Remember 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 sign.
  • Value of the ID attribute: This represents the ID value we use to locate the element.

Syntax:

css=(Html tag )(#) (value of the ID attribute)

Example:

Below is the DOM part indicating the First Name field on the Register Account page of the TestMu AI eCommerce Playground website.

Tag and ID in CSS Selector
<input type="text" name="firstname" value="" placeholder="First Name" id="input-firstname" class="form-control">

Here is how you can locate the required WebElement using the cssSelector:

driver.findElement(By.cssSelector("input#input-firstname"))

Tag and Class in CSS Selector

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

Syntax:

css=(HTML tag)(.)(Value of Class attribute)

Example:

Here is the DOM snapshot and the corresponding command to access the required WebElement using CSS Selector in Selenium for the Login button on the Account Login page of the TestMu AI eCommerce Playground website.

Tag and Class in CSS Selector
<input type="submit" value="Login" class="btn btn-primary">

Tag and Attribute

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

Syntax:

css=(HTML Page)[Attribute=Value]

Example:

Here is the DOM structure:

<input type="phone" placeholder="Phone*" name="phone" value="" class="form-control sign-up-input-2 ">

Here is how the WebElement – ‘phone’ can be located using the cssSelector in Selenium.

driver.findElement(By.cssSelector("input[name="phone"]"))

Tag, Class, and Attribute

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

Syntax:

css=(HTML tag>)(. )(Class attribute value)([attribute=Value of attribute])

Let’s locate the Submit button on the Input Form Demo page on the TestMu AI Selenium Playground website.

Tag, Class, and Attribute

Here is the DOM structure of the WebElement for the Submit button.

<button type="submit" class="bg-lambda-900 hover:bg-transparent hover:text-lambda-900 border border-lambda-900 text-white rounded p-10 focus:outline-none w-180 selenium_btn py-5 px-10 rounded">Submit</button>

Here is how you can locate the Submit button:

driver.findElement(By.cssSelector("button.bg-lambda-900[type="submit"]"));

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

CSS Selector in Selenium helps in matching multiple strings through the use of multiple patterns like ^, $, *. Wildcard selectors in CSS are used to select various elements simultaneously.

Here is how wild cards can be effectively used with the CSS Selector in Selenium:

  • 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:

    css=(HTML tag)([attribute^=start of the string])
    

Example:

Here is the DOM structure for locating the WebElement:

    <input type="email" name="email" value="" placeholder="Email" required="required" autofocus="autofocus" class="form-control mt-3 form-control-lg">
    

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

    driver.findElement(By.cssSelector("input[name^='em']"));
    
  • 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:

    css=(HTML tag)([attribute$=end of the string])
    

Example:

Here is the DOM structure of the element:

    <input type="email" name="email" value="" placeholder="Email" required="required" autofocus="autofocus" class="form-control mt-3 form-control-lg">
    
    </li>
    </ul>
    

Here is how ends-with in CSS Selector is used for locating the required WebElement:

    driver.findElement(By.cssSelector("input[name$='ail']"));
    
  • Contains in CSS Selector
    This helps locate elements when we try to match elements with a string containing a designated value.

Syntax:

    css=(HTML tag)([attribute*=partial string])
    

Example:

Here is the DOM structure to locate the element:

<input type="email" name="email" value="" placeholder="Email" required="required" autofocus="autofocus" class="form-control mt-3 form-control-lg">

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

driver.findElement(By.cssSelector("input[class*='control']"));

Child Elements in CSS Selector

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

Example:

To demonstrate the use of child elements in CSS Selector, we will locate the menu links on the TestMu AI Selenium Playground home page.

Child Elements in CSS Selector

Here is the DOM structure to locate the element:

<ul class="list-disc pl-10 pb-30 grid grid-cols-4 w-full gap-10 mt-30 smtablet:grid-cols-1"><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/ajax-form-submit-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Ajax Form Submit</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/auto-healing" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Auto Healing</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/bootstrap-alert-messages-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Bootstrap Alerts</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/bootstrap-date-picker-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Bootstrap Date Picker</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/bootstrap-dual-list-box-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Bootstrap List Box</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/bootstrap-modal-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Bootstrap Modals</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/bootstrap-download-progress-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Bootstrap Progress bar</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/broken-image" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Broken Image</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/checkbox-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Checkbox Demo</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/context-menu" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed"> Context Menu</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/data-list-filter-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Data List Filter</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/download-file-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Download File Demo</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/drag-drop-range-sliders-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Drag &amp; Drop Sliders</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/drag-and-drop-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Drag and Drop</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/dynamic-data-loading-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Dynamic Data Loading</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/generate-file-to-download-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">File Download</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/geolocation-testing" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Geolocation Testing</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/hover-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Hover Demo</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/iframe-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">iFrame Demo</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/input-form-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Input Form Submit</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Javascript Alerts</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/jquery-date-picker-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">JQuery Date Picker</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/jquery-download-progress-bar-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">JQuery Download Progress bars</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/jquery-dual-list-box-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">JQuery List Box</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/jquery-dropdown-search-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">JQuery Select dropdown</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/key-press" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Key Press</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/nested-frames" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Nested Frames</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/overlapped-element" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed"> Overlapped Element</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/bootstrap-progress-bar-dialog-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Progress Bar Modal</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/radiobutton-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Radio Buttons Demo</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/redirection" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed"> Redirection</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/select-dropdown-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Select Dropdown List</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/shadow-dom" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed"> Shadow DOM</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/simple-form-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Simple Form Demo</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/status-code" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed"> Status Codes</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/table-data-download-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Table Data Download</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/table-search-filter-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Table Data Search</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/table-records-filter-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Table Filter</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/table-pagination-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Table Pagination</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/table-sort-search-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Table Sort &amp; Search</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/upload-file-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Upload File Demo</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/virtual-dom" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed"> Virtual DOM</a></li><li class="pt-10"><a href="https://www.lambdatest.com/selenium-playground/window-popup-modal-demo" class="text-black text-size-14 hover:text-lambda-900 leading-relaxed">Window Popup Modal</a></li></ul>

To locate elements, the following syntax would be used:

Css= tagname.class name li:nth-of-child(index of the referenced child which in our case is 3)

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

driver.findElement(By.cssSelector(".container__selenium ul > li:nth-child(1) > a");

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

Css= .container__selenium ul li
    driver.findElement(By.cssSelector(".container__selenium ul li:last-child");

Relative Locators in Selenium WebDriver

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 the Selenium 4 framework offers. Here is a short gist of relative locators in Selenium 4:

Locator TypeDescriptionSyntax (in Java)
aboveWebElement is above the specified elementdriver.findElement(with(By.tagName(“TagName”)).above(ElementName));
belowWebElement is below the specified elementdriver.findElement(with(By.tagName(“TagName”)).below(ElementName));
toLeftOfWebElement is to the left of an elementdriver.findElement(with(By.tagName(“TagName”)).toLeftOf(ElementName));
toRightOfWebElement is to the right of an elementdriver.findElement(with(By.tagName(“TagName”)).toRightOf(ElementName));
nearWebElement is within 50 pixels of an elementdriver.findElement(with(By.tagName(“TagName”)).near(ElementName));
Note

Note: Automate your Selenium testing across 3000+ real environments. Try TestMu AI Today!

Demo: Relative Locators in Selenium WebDriver

To demonstrate the usage of relative locators in Selenium 4, we will locate the WebElements on the TestMu AI eCommerce Playground page. The following test scenario will be automated using the relative locators in Selenium WebDriver. The tests will be run on the TestMu AI cloud grid on the latest version of Chrome browser on the Windows 10 platform.

TestMu AI is an AI-powered test orchestration and execution platform that lets developers and testers perform automation testing at scale on an online browser farm of 3000+ real browsers and operating systems.

Test Scenario

  • Locate the WebElement for the iMac product on the product page.
  • Locate the WebElement for the iMac product price displayed below the iMac product using the relative locator.
  • Locate the Apple Cinema 30 product, displayed to the right of the iMac product, using the toRightOf relative locator.
  • Locate the iPod Nano product displayed above the Apple Cinema 30 product using the above relative locator.
  • Locate the iPod Shuffle product displayed to the left of the iPod Nano product using the toLeftOf relative locator.
  • Perform assertions on every WebElement after locating the WebElement and getting its text.
...Relative Locators in Selenium WebDriverLambdaTest eCommerce Playground

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

WebElement FirstElement = driver.findElement(By.Id("idvalue"));

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

driver.findElement(with(By.tagName("tagName")).below(FirstElement));

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

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

public class LocatorTests {
    WebDriver driver;
    String username = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME");
    String accesskey = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY");
    String gridURL = "@hub.lambdatest.com/wd/hub";

    @BeforeTest
    public void setup() throws MalformedURLException {
        ChromeOptions browserOptions = new ChromeOptions();
        browserOptions.setPlatformName("Windows 10");
        browserOptions.setBrowserVersion("122.0");
        HashMap&lt;String, Object> ltOptions = new HashMap&lt;String, Object>();
        ltOptions.put("project", "Selenium Locator Demo");
        ltOptions.put("w3c", true);
        ltOptions.put("plugin", "java-testNG");
        ltOptions.put("build", "Demonstration: Selenium Locator Demo on LambdaTest");
        browserOptions.setCapability("LT:Options", ltOptions);

        driver = new ChromeDriver();
        driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), browserOptions);

    }

    @Test
    public void testRelativeLocator() {

        driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=product/manufacturer/info&manufacturer_id=8");


        WebElement iMac = driver.findElement(By.linkText("iMac"));
        WebElement iMacPriceViaBelow = driver.findElement(with(By.cssSelector("div.price> span")).below(iMac));
        assertEquals(iMacPriceViaBelow.getText(), "$170.00");

        WebElement fetchToTheRight = driver.findElement(with(By.tagName("h4")).toRightOf(iMac));
        assertEquals(fetchToTheRight.getText(), "Apple Cinema 30"");

        WebElement fetchViaAbove = driver.findElement(with(By.tagName("h4")).above(fetchToTheRight));
        assertEquals(fetchViaAbove.getText(), "iPod Nano");

        WebElement fetchViaToLeftOf = driver.findElement(with(By.tagName("h4")).toLeftOf(fetchViaAbove));
        assertEquals(fetchViaToLeftOf.getText(), "iPod Shuffle");

    }
    @AfterTest
    public void teardown() {
        driver.quit();
    }

}

Code Walkthrough

As the tests will run on the TestMu AI cloud platform, we need to provide the TestMu AI Username and Access Key. These credentials can be found on your TestMu AI Profile > Account Settings > Password & Security.

Code Walkthrough

The credentials are confidential values that should not be hardcoded in the code. The following line of code will help set the Username and Access Key using the environment variables. The gridURL helps connect the remote session to the TestMu AI cloud grid.

gridURL helps connect the remote session

Next, we need to set the TestMu AI automation capabilities to set the platform, browser and its version, build name, test name, and other mandatory options required for running the tests on the TestMu AI platform.

The TestMu AI Capabilities Generator helps in easily setting the capabilities by selecting the desired options from the UI. It provides the auto-generated code that can be used directly in the code.

 LambdaTest Capabilities Generator

The following lines of code sets the capabilities for running the test on Chrome browser version 122.0 on the Windows 10 platform.

 test on Chrome browser version

ChromeOptions class is used as we need to run the tests on the Chrome browser. Similarly, if we need to run the tests on Edge browser, we can use EdgeOptions and likewise for other browsers. Finally, a new instance of RemoteWebDriver is created by supplying the username, accesskey, and gridURL with the browserOptions variables.

The @BeforeTest annotation in TestNG placed on the top of the setup() method will run this method before any of the tests, so the configuration for running the test on the TestMu AI platform is set correctly.

annotation in TestNG placed on the top of the setup

The testRelativeLocator() method will run the test by locating the WebElements using the below, toRightOf, above, and toLeftOf relative locators, as discussed in the test scenarios.

 testRelativeLocator() method will run the test

After all the tests are run successfully, the driver session will be closed when the driver.quit() statement is invoked. This statement will be called after each test as the @AfterTest annotation of TestNG has been used above the tearDown() method.

Test Execution

The following screenshot shows the output of the test execution performed using IntelliJ IDE:

 relative locators to locate the desired WebElement

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

WebElement fetchwithmutipleRelative=driver.findElement(with(By.tagName("h4")).below(fetchviatoLeftOf).toRightOf(fetchviaabove));

The above code identifies an element below a given WebElement and to the right of the newly searched element.

Also, subscribe to the TestMu AI YouTube Channel and get detailed tutorials around Selenium automation, Appium automation, and more.

...

Best Practices to Use Locators in Selenium WebDriver

The main challenge in writing test 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.

  • Use a unique ID for element identification: The first and foremost 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 or non-existent element. 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 target element you want to click or locate, not other elements 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 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 using the locateElement() or locateElementBy*() methods. You can navigate to any element on the page using the browser’s address bar, locator parameters, and values, as well as 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, use locators such as CSS and XPath instead of IDs, as they never change their value. The second thing you should do is watch those values after each run. So, if we want to locate an element with an ID of the tooltip using the browser’s address bar, we should run and watch the values of those IDs to identify whether they are auto-generated.

  • Don’t use XPath or CSS Selector provided by the developer 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. However, most suggest using XPath or CSS Selectors provided by the browser developer tools.
  • However, if you use XPath or CSS Selectors provided by the browser developer tools, your tests will not work if the source code changes. To have stable tests, you should use locators independent of HTML structure.

  • Avoid using the locators that change dynamically on page refresh: While working on some websites, it can be observed that the locators, such as ID or class name, change dynamically on page load or refresh. It should be noted that in such situations, the ever-changing locators, i,e. IDs and class names should not be used.
  • Locators such as CSS Selector or XPath should be used here to avoid test flakiness. Using these locators can help in creating more robust test scripts.

  • Avoid using XPaths heavily in the project: Many testers blindly keep on using the XPaths heavily in the project. Testers make the mistake of adding test scripts containing XPath to locate the WebElement, which internally calls the ID locator itself.
  • Use explicit waits: Explicit waits in Selenium WebDriver should ensure that the WebElement is present and visible before the automated tests interact with that WebElement. This can help in avoiding test flakiness.
  • Moreover, you can also leverage the SmartWait feature by TestMu AI as well. TestMu AI SmartWait executes a series of actionability checks on webpage elements before executing any actions. These checks include verifying elements for visibility and intractability to ensure they are ready for actions like clicking or typing.

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 various 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. Now that you have learned how to use locators and relative locators in Selenium WebDriver, you should be able to work with locators effectively. Hope this tutorial has helped you learn everything there is to know about using locators in the Selenium WebDriver.

Author

Mohammad Faisal Khatri is a Software Testing Professional with 17+ years of experience in manual exploratory and automation testing. He currently works as a Senior Testing Specialist at Kafaat Business Solutions and has previously worked with Thoughtworks, HCL Technologies, and CrossAsyst Infotech. He is skilled in tools like Selenium WebDriver, Rest Assured, SuperTest, Playwright, WebDriverIO, Appium, Postman, Docker, Jenkins, GitHub Actions, TestNG, and MySQL. Faisal has led QA teams of 5+ members, managing delivery across onshore and offshore models. He holds a B.Com degree and is ISTQB Foundation Level certified. A passionate content creator, he has authored 100+ blogs on Medium, 40+ on TestMu AI, and built a community of 25K+ followers on LinkedIn. His GitHub repository “Awesome Learning” has earned 1K+ stars.

Close

Summarize with AI

ChatGPT IconPerplexity IconClaude AI IconGrok IconGoogle AI Icon

Frequently asked questions

Did you find this page helpful?

More Related Hubs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests