The Basics of Selenium: Mastering Selenium Locators

Dulmini Attanagoda
7 min readDec 26, 2023

--

Let’s understand the concept of Locators in Selenium

Hi guys 👋 This is the 2nd one on our Selenium blog post series. In this post, we will focus mainly on Selenium Locators. The first step will be to introduce Locators, and then we will dig deeper into different use cases of Locators, including coding examples.

What are Locators in Selenium?

One of the most crucial elements of automated testing in Selenium is Locators. To put it simply, Locators are a special identification that Selenium Web Drivers use to find a particular web element on a webpage. When automating a web application with Selenium, you must interact with web elements like buttons, links, checkboxes, and input fields.

To interact with these web elements, you must locate them using special Selenium Locators. An id, name, class name, CSS selector, or XPath expression can all be used as Locators. Then you can give Selenium instructions to locate a web element and execute an action on it, like clicking a button, completing a form, or choosing an item from a drop-down menu, by using a Locator.

How to Locate a Web Element in DOM?

You can follow the mentioned steps to identify the web element in DOM on a web browser.

Step 01 — Open the relevant web page.

Step 02 — Right-click on the web page and select the inspect option.

Figure 1 — How to Choose Inspect Option

Step 03 — The following example describes the way to find the web element in the DOM. First, click on the mouse icon arrow in the screenshot (1). And place the mouse pointer in the selected component (2), and this should automatically highlight the component. As a result, it automatically highlights the HTML element on the DOM (3).

Figure 2 — Inspecting the Element in Detail

Different Types of Selenium Locators

You can use a variety of locators in Selenium to find specific web elements on a webpage. The locators that are most often used are,

className: To identify an object, the ‘className’ operator uses the class attribute.

cssSelector: CSS is used to create style rules for webpages and can be used to identify any web element.

id: The ‘id’ attribute can also identify elements, just like the class does.

linkText: We can locate elements through the text utilized in hyperlinks.

name: An element can also be identified by its name attribute.

partialLinkText: We can use a part of the text in the link to identify an element.

tagName: Another way is to use a tag to find elements.

xpath: The query language for the XML document is called ‘xpath’. The web element on any page can be uniquely identified.

Figure 3 — Accessing elements through Locators

Locate Elements by ‘id’

One of the most popular methods for finding elements on a web page is to use ‘id’ as a locator.

With the support of an example, let’s learn how to locate a web element using the ‘id’ attribute. Let’s consider the following ‘input’ element.

<input aria-invalid="false" autocomplete="email" class="D8X Hsu tBJ dyH iFc sAJ L4E Bvi iyn H_e pBj qJc TKt LJB xD4 z-6" id="email" name="id" placeholder="Email" spellcheck="false" type="email" value="">

As we can see, the attribute ‘id’ is contained by the HTML tag inside the input tag. Here, the ‘id’ used is ‘email’, which helps us find this element on the page. We can now use the following syntax to locate the ‘email’ text box on the webpage.

By.id("email")

Here, after finding the element using ‘id’ attribute, we can perform some actions on the element. For example, if you want to type or send any information onto the HTML page after finding an element, then use the ‘sendKeys()’ method.

driver.findElement(By.id("email")).sendKeys("academytest@gmail.com");

The ‘findElement()’ method is used to locate an HTML element on the web page. In this case, it’s finding an element using its ‘id’ attribute. The value passed to By.id(“email”) indicates that the script is looking for an element with the ‘id’ attribute set to ‘email’.

Once the element with the specified ‘id’ is found, the .sendKeys() method is used to simulate keyboard input. In this case, it’s entering the email address “qatest@gmail.com” into the input field associated with the ‘email’ id.

Locate Elements by ‘name’

Selenium provides users with an additional means of identifying an element through the name attribute, which is similar to the id attribute. On the other hand, unlike ‘id’, a web page can contain more than one element with the same ‘name’ attribute. Thus, we must always ensure that the name attribute has a unique value if we plan to use it to identify a single web element. If not, it might identify multiple elements with the same name value on the same page.

Selenium will simply choose the first values on the page that match the search parameters. With the aid of an example, let’s learn how to locate a web element using the ‘name’ attribute. Let’s consider the following ‘input’ element.

 <input aria-invalid="false" autocomplete="new-password" class="D8X Hsu tBJ dyH iFc sAJ L4E Bvi iyn H_e pBj qJc TKt LJB xD4 BMi z-6" id="password" name="password" placeholder="Password" spellcheck="false" type="password" value="" aria-autocomplete="list">

We can see the attribute ‘name ‘ with the value ‘password’. We can use the following syntax to locate the web element using the ‘By’ class.

By.name("password")

In this case, it’s finding an element using its “name” attribute. The value passed to By.id(“password”) indicates that the script is looking for an element with the “name” attribute set to “password”.

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

Once the element with the specified name attribute (“password”) is located, the method is employed to simulate keyboard input. In this case, the text "tesT@123" is being entered into the password input field.

driver.findElement(By.name("password")).sendKeys("tesT@123");

Locate Elements by Class Name

Based on the class values, Selenium can locate web elements by using ClassName. For instance, we can use the class to identify the form element and continue any necessary activities.

driver.findElement(By.className("red")).click();

Locate Elements by CSS

CSS (Cascading Style Sheets) Selectors in Selenium are used to identify and locate web elements based on their ‘id’, ‘class’, and other attributes. CSS is a preferred locator strategy as it is simpler to write and faster as compared to XPath.

The following describes the basic syntax for identifying a web element with CSS.

css = Tagname[attribute=value]

Let’s consider the following ‘anchor’ element.

<a class="bodySmall form-footer" href="/secure/9521/identity/forgot_password">Forgot Password</a>
a[href='/password/reset/']
driver.findElement(By.cssSelector("a[href='/password/reset/']")).click();

Locate Elements by XPath

Mainly ‘XPath’ is used to locate web page elements by passing the XML expressions. Similar to CSS selectors, ‘XPath’ is quite useful in locating dynamic elements on a webpage. ‘XPath’ can access any element present in the webpage even when they have dynamic properties.

XPath can be accessed using the following syntax.

//tag_name[@attribute_value]

Let’s consider the following ‘input’ element for this example.

<input aria-invalid="false" autocomplete="email" class="D8X Hsu tBJ dyH iFc sAJ L4E Bvi iyn H_e pBj qJc TKt LJB xD4 z-6" id="email" name="id" placeholder="Email" spellcheck="false" type="email" value="">

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

driver.findElement(By.xpath("//input[@placeholder='Email']"))

Locate Elements by LinkText

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

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

<a class="Wk9 CCY S9z eEj kVc xQ4 uCz iyn" href="/password/reset/" rel="">Forgotten your password?</a>

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

driver.findElement(By.linkText("Forgotten your password?"))

The following code block demonstrates how to test login scenarios for a web page. It also demonstrates how to come up with an approach to test the forgot password scenario as well.

package testapp;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


import java.time.Duration;

public class SeleniumTest {
public static void main (String[]args){
// set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver","C:\\Users\\HP\\Downloads\\chromedriver-win64\\chromedriver.exe");
// initialize the ChromeDriver instance
WebDriver driver = new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
// Open the Web page
driver.get("https://www.pinterest.com/login/");

// Test Login
driver.findElement(By.id("email")).sendKeys("academytest@gmail.com");
driver.findElement(By.name("password")).sendKeys("tesT@123");
driver.findElement(By.className("red")).click();

// Test Forgot Password
driver.findElement(By.cssSelector("a[href='/password/reset/']")).click();
driver.findElement(By.linkText("Forgotten your password?")).click();
driver.findElement(By.xpath("//input[@placeholder='Email']")).sendKeys("academytest@gmail.com");

driver.quit();


}

}

Conclusion

  • In this post, we mainly focused on Locators in Selenium.
  • First, we understood, what are Locators in Selenium. Then, we discussed different types of Locators in Selenium.
  • After the discussion, I have demonstrated how to access elements by those different types of Locators.

Thank you for reading🎉. Let’s meet on our next blog post from this series. Until then, keep smiling, and stay curious! 🤓✨

--

--