What is Locator in Selenium with Example? A Detailed Guide (2024)

Last updated on : Jun 26, 2023 by Shubham Srivastava

Do you want to learn about- What is Locator in Selenium Framework? and How do Locators work in Selenium?

Great !! In this Selenium Guide, we will learn about Selenium Locators, Why do we need locators in Selenium?, Which one is the best locator in Selenium WebDriver?, and some Selenium Interview Level Questions based on Locators as well. So, without any further delay, Let’s start with our today’s agenda : What is Locator in Selenium Framework?

Locator in Selenium - How to use locators in selenium ?

What is Locator in Selenium? – Key Points

  1. Locators are used to identify and locate elements on a web page for test automation in Selenium.
  2. Locators define the strategy or mechanism by which Selenium finds and interacts with specific elements on the page.
  3. As of now, there are overall 8 Locators available in Selenium, using which we can try to identify any web element on the web page.
  4. In Selenium, some locators work with some specific attributes of a Web Element (such as ‘id’, ‘classname’, ‘name’), while some locators work with their ‘Tag Name’, on the text or part of text contained by that Web Element.
  5. Overall, A locator in Selenium – allows us to select one or more Web Elements to perform action on them as per the test plan.

Regarding Selenium Framework, it provides several types of locators to locate elements based on different attributes, entities and properties of Web Elements. Below are some commonly used locators in Selenium WebDriver or Selenium Grid.

Note** This in-depth Selenium tutorial is part of our free Selenium Framework Mastery Series. In case, if you are also interested to learn about other important topics of Selenium, then check the link after this Selenium guide.


Types of Locators in Selenium Framework with Example

There are various type of Locators available in Selenium framework that allow us to select one or more Web Elements to perform action on them as per the test plan. Let’s see what the different types of Locators available in Selenium to identify web element(s) –

LocatorLocator DetailSelenium Code Example of Locators
idTo search web elements using their id attribute value.WebElement btn = driver.findElement(By.id("Element id attribute value"));
nameLocating web elements using their name attribute value.driver.findElement(By.name("Element 'name' attribute value"));
class nameTo find web elements using their class attribute values.driver.findElement(By.className("Element 'class' attribute value"));
tag nameLocating web elements using their tag name.driver.findElement(By.tagName("Element tag name"));
link textTo identify the hyperlinks on a web page – Anchor tags (<a>), using text written inside it.driver.findElement(By.linkText("Full text present in Element to be visible on UI"));
partial link textTo identify the hyperlinks on a web page – Anchor tags (<a>), using part of text written inside it.driver.findElement(By.partialLinkText("Partial Text present in Element, to be visible on UI"));
css selectorFinding web element using an element selector and a selector value that can identify particular elements on a web page.driver.findElement(By.cssSelector("Any CSS Selector formula, to locate the element"));
xpathTo locate web elements by provide xml path of that web element.driver.findElement(By.xpath("Path of the Element in the XML DOM Document (Web Page)"));

Selenium Interview Tips 💡
In most of the SDET / Automation Testing related interview, one question is definitely asked based on Types of Locators in Selenium Framework. So prepare it extremely well. !!


How to use Locators in Selenium?

As described in below image, we can understand what is tag name? what is an attribute? and how to identify values of attributes?. We create a Locator pattern / formula and search any specific web element based on these type of properties only.

What-is-Locator-in-Selenium-Explained-with-Example-LogicalDuniya_com.

Locate Web Element using ‘id’ attribute

If you want to locate an input web element which has id attribute and value, similar to above image example, then you can something like below Selenium code to locate that Web Element and perform action on it-

// locate the Email input field using id attribute -
WebElement emailInputElement = driver.findElement(By.id("email"));

// perform action on that found Email input field - 
emailInputElement.clear();
emailInputElement.sendKeys("logicalduniya@gmail.com");  // Entering email id in the input box

Note : It is highly recommended to use the id attribute in order to locate Web Element.


Locate Web Element using ‘class’ attribute

In Selenium test cases, To find a WebElement using it’s class attribute values, we need to use By.className("...") method. In this method, we need to pass the value of class attribute. Below is a sample Selenium script to find an <input> web element which is having a class attribute –

Web Page DOM Structure –

<td>
    <input type="email" class="email-cls" name="user-email">
</td>

Selenium Code to Locate Web Element using ‘class’ –

// locate the Email input field using class attribute -
WebElement emailInputElement = driver.findElement(By.className("email-cls"));

// perform action on that found Email input field - 
emailInputElement.clear();
emailInputElement.sendKeys("logicalduniya@gmail.com");  // Entering email id in the input box

Note : It is less recommended to use the class attribute in order to locate Web Element, because same class value can be given to multiple Web Element, which may cause script failure if not handled properly.


Locate Web Element using ‘name’ attribute

Let’s pick same example of Email input box as above. If you want to locate this Web Element using its name attribute, then in Selenium there is a dedicated method available for that, which is By.name("...").

Below is the structure of DOM around that Web Element, and the Selenium script to locate that Email web element –

Web Element DOM Structure in Webpage –

<td>
    <input type="email" class="email-cls" name="user-email">
</td>

Selenium Code to Locate Web Element using ‘name’ –

// locate the Email input field using name attribute -
WebElement emailInputElement = driver.findElement(By.name("user-email"));

// perform action on that found Email input field - 
emailInputElement.clear();
emailInputElement.sendKeys("logicalduniya@gmail.com");  // Entering email id in the input box

Note : It is highly recommended to use the name attribute in order to locate Web Element, because the value of name attribute is unique for each web element.


Locate Web Element using ‘Tag Name’

Let’s say, on a Web Page, there is an Image of some height and width, and in your test script, you want to validate its height and width. Then, along with above locators, you can use its tag name ‘img‘, to find that web element and perform action on it.

When you want to use tag name to search for a web element, then make sure How many other web elements are available with that tag name. Because, if there are multiple elements with same tag name, then you need to use findElements(..) method to find all such web element and then you need to traverse in the list to pick you’re required web element.

There is a class in Selenium library, to get height and width of any Web Element, and class name is ‘Dimension‘. This class has 2 main methods –

  1. int getHeight()
  2. int getWidth()

And, Using this Dimension class and the above methods, we will find out the height and width of Web Element. Below is the structure of DOM around that Web Element, and the Selenium script to locate that Email web element –

Web Element DOM Structure in Webpage –

<!DOCTYPE html>
<html>
<h2> Logical Duniya - Selenium Locators Tutorial</h2>
<p>
    <img
        src="https://www.logicalduniya.com/images/selenium-basics-logo.png"
        alt="console" class="aligncenter size-full"
        height="768" width="1366"
    />
</p>
</html>

Selenium Code to Locate Web Element using Tag Name –

// Search for that Image element (supposing, there is only 1 image element on the entire web page) - 
WebElement imageLogo = driver.findElement(By.tagName("img"));

// To get the height & width, we need to create object of Dimension class - 
Dimension dim = imageLogo.getSize();

// To get the values of height & width, call the methods -
System.out.println("\nOutput -\n--------");
System.out.println("LogicalDuniya Logo Image Height ==> "+ dim.getHeight() );
System.out.println("LogicalDuniya Logo Image Widht ==> "+ dim.getWidht() );

Output of Selenium Program –

Output -
--------
LogicalDuniya Logo Image Height ==> 768
LogicalDuniya Logo Image Widht ==> 1366

Note: It is not recommended to use the tag name to find out Web Element. Because, there are high chances, there might multiple Web Element exist with same tag name, which may cause script failure if not handled properly.


Locate Web Element using ‘Link Text’

There might be some cases, when you want to find some hyperlink web elements where no proper / unique attribute are provided by developers. In that case, link text plays a crucial role to find out such web elements.

Selenium provides findElement(By.linkText("---")); method to find out such Web Elements. When you want to use this method, just make sure there is NO other web element exist, which is displaying same text on UI.

DOM Structure of Web Element in Webpage –

<ul>
    <li id="login-item" class="menupop">
        <a class="login-link" href="https://logicalduniya.com/login/">Login to LogicalDuniya.com</a>
    </li>
</ul>

Selenium Code to Locate Web Element using Link Text –

// Locating the hyperlink using linkText(..)
driver.findElement(By.linkText("Login to LogicalDuniya.com")).click();					

// Get title of traversed web page -
System.out.println("\nOutput -\n--------");
System.out.println("Link is Clicked and Reached to new webpage.\nTitle of new webpage is ==> " 
     + driver.getTitle());

Output –

Output -
--------
Link is Clicked and Reached to new webpage.
Title of new webpage is ==> Login

Note : Link Text locator works in a Case Sensitive manner. Means, if the link contains text as ‘Login’ and you are looking for text ‘login’, then your script would NOT able to find that web element.


Locate Web Element using ‘Partial Link Text’

Partial Link Text works similar to Link Text, but when using this locator, it is not necessary that the link should contain exact given text. Using this locator, you can find a link web element by providing part of visible text of it. Below is an example –

DOM Structure of Web Element in Webpage –

<ul>
    <li id="login-item" class="menupop">
        <a class="login-link" href="https://logicalduniya.com/login/">Login to LogicalDuniya.com</a>
    </li>
</ul>

Selenium Code to Locate Web Element using Partial Link Text –

// Locating the hyperlink using partialLinkText(..)
driver.findElement(By.partialLinkText("Login")).click();					

// Get title of traversed web page -
System.out.println("\nOutput -\n--------");
System.out.println("Link is Clicked and Reached to new webpage using Partial Link Text.\nTitle of new webpage is ==> " 
     + driver.getTitle());

Output –

Output -
--------
Link is Clicked and Reached to new webpage using Partial Link Text.
Title of new webpage is ==> Login

Locate Web Element using ‘CSS Selector’

CSS Selector is a pattern or in simple terms – a formula, that uses CSS to prepare a pattern and search for the web elements. The CSS Selectors basically use the character sequence pattern, which identifies the web elements based on their HTML structure, attributes or values.

Searching for an element on a web page using CSS selector may seem a little difficult than using attributes like id, name, link, etc. but it’s one of the most efficient strategies to locate dynamic elements that don’t have consistent HTML attributes. Let’s see an example of How to write CSS Selector in Selenium using class or other any other attribute?

Illustration of CSS Selector usage –

DOM Structure of Web Element in Webpage –

<div>
    <label>Email:</label>
    <input name="email" type="text" class="email-input-box" />
    <input type="hidden" name="url" value="https://www.editpad.org/" />
</div>

Selenium Code to Locate Input Element using CSS Selector Locator –

// Locating web element using CSS Selector -
WebElement emailInputElement = driver.findElement(By.cssSelector(".email-input-box"));

// Entering an email id to the found email box-
emailInputElement.clear();
emailInputElement.sendKeys("logicalduniya.com");

There are many other ways to write CSS Selector patterns. We will learn about them in this CSS Locators session.


Locate Web Element using ‘XPath’?

‘XPath’ is another very popular locator to identify single or group of Web Elements.

XPath or (XML Path Language) is a powerful language used to navigate and query XML documents, including HTML documents. In Selenium, XPath is commonly used as a locator strategy to locate elements on a web page.

XPath allows you to define the path to an element by traversing the structure of the XML/HTML document. It provides a flexible way to locate elements based on various attributes, tag names, text content, and their relationships with other elements in the document.

Here’s a basic syntax for writing XPath expressions:

  1. Selecting elements by tag name:
    • Example: //tagname
    • This selects all elements with the specified tag name, regardless of their position in the document.
  2. Selecting elements by attributes:
    • Example: //*[@attribute='value']
    • This selects all elements that have the specified attribute with the matching value.
  3. Selecting elements by attribute partial value:
    • Example: //*[contains(@attribute, 'value')]
    • This selects all elements that have the specified attribute containing the given value.
  4. Selecting elements by text content:
    • Example: //*[text()='content']
    • This selects all elements that have the specified text content.
  5. Selecting elements based on their relationship with other elements:
    • Example: //parentTag/childTag
    • This selects all child elements of a parent element based on their tag names.

Let’s take an above explained scenario 4 – xpath to find element by text.

Locate Web Element using xpath

DOM Structure of Web Element in Webpage

<a href="https://logicalduniya.com/">
    ...
    <br />
    <h3 class="LC20lb MBeuO DKV0Md">Welcome To LogicalDuniya - Learn Full Stack Development</h3>
    ...
</a>

Selenium code with XPath to find Element-

// Locating the WebElement - 
WebElement googleResultElement1 = driver.findElement(By.xpath("//*[text()='Welcome To LogicalDuniya - Learn Full Stack Development']"));

// Performing action on it -
googleResultElement1.click();

Selenium Interview Tips 💡
In all of the SDET / Automation Testing related interviews, you’ll be definitely asked to write XPath to locate web element in Selenium. So practice it extremely well. !!


Conclusion

In this Selenium Tutorial, we have learnt about What is Locator in Selenium? and Different types of Locators in Selenium Framework? We also understood, How to use each of the Locators in Selenium with well explained pictorial illustration and Selenium code. We have also seen, some of the most popular Selenium Interview Question for Beginners and Intermediate level folks. In case, if you have any query related to Free Selenium Framework Mastery Series, Programming, Resume or Career, then just drop your query in the below comments section, and I’ll try my best to provide answer to your query within 24 hours.

Keep thinking logical…
Cheers,
Shubham !!

Shubham

Shubham Srivastava

Hey there, my name is Shubham and I'm working as an SDET at a US based FinTech company. I've more than 7 years of working experience and using my knowledge - I want make this platform super helpful for those, who want to solve any software development and testing related problems. Comment your query / request or suggestion in the below section, and I'll try to respond within 24 hours. Keep improving, Keep coding !!

Recommended Posts :


4 1 vote
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

[…] XPath Locator in Selenium – A Detailed Guide by LogicalDuniya.com […]

Press ESC to close