What are Locators in Selenium?

Selenium has grown to be the most widely used tool among developers for web application automation testing over the last 10 years. The Selenium suite is incredibly flexible; teams may use it to run tests on a local computer or in the cloud, and it interfaces with a wide range of widely used programming languages. Before reading this article, consider reading the principles of software testing for a better understanding of locators in selenium.

Although selenium presents certain obstacles, its versatility makes it the ideal testing framework to use. Explore the various locators in Selenium in this post, including ID, XPath, Name, DOM, Link, Tag, and others that help testers choose and interact with an HTML DOM element.

Get Started with Selenium Locators

Locators in Selenium were briefly covered in our article on using Python to get started with the Selenium framework. The following are the general procedures to run a test using Selenium:

  1. Get browser drivers here.
  2. Launch a Selenium WebDriver and load websites
  3. Execute specific tasks inside a predetermined test.
  4. Determine whether the test produced the intended results.
  5. Close the WebDriver

After the Selenium WebDriver is initialized and has loaded the webpage for testing, the Selenium locators kick in in the fourth step above. Testers can choose which HTML DOM element to interact with by using a locator. The top 8 locators in Selenium WebDriver are explored in this post. Developing more effective automation scripts requires an understanding of how to employ various locators. The test will fail before it even gets started if the script is unable to determine which element it needs to interact with. Explore what’s new in Selenium here.

Types of Locators in Selenium

An overview of the top 8 locators in Selenium is here:

  • CSS ID: find_element_by_id
  • CSS class name: find_element_by_class_name
  • Name attribute: find_element_by_name
  • DOM structure or Xpath: find_element_by_xpath
  • TagName: find_element_by_tag_name()
  • Link text: find_element_by_link_text
  • Partial link text: find_element_by_partial_link_text
  • HTML tag name: find_element_by_tag_name

Even though all of these locators only yield one element, the ‘.find_elements()’ technique can locate several things. Let’s explore the various locators in Selenium and their applications in more detail. This concept is one of the popular Selenium interview questions and answers.

CSS ID to Locate Elements 

Finding an element can be done much more easily using this approach. Design-wise, each element on the page has a unique CSS ID, which is kept in the id property of an HTML DOM element. As a result, an ID can uniquely identify an element.

The ‘.find_element_by_id()’ function of the WebDriver class must be used to utilize this capability. Its usage is as follows:

from selenium import webdriver

driver = webdriver.Chrome(‘./chromedriver’)

driver.get(“https://www.python.org”)

search_bar = driver.find_element_by_id(“id-search-field”)

A try-catch block can be used to handle a NoSuchElementException that is raised when there isn’t a DOM element with the ID that the search is looking for.

In theory, each DOM element on a page ought to have its own ID. But this is not something that is typically observed in real life. It’s possible that two elements have the same ID or that the majority of elements don’t have one. In these situations, a new approach is required to uniquely identify a DOM element. 

Suggested Read: How to Answer the ‘Tell Me About Yourself’ Interview Question.

CSS Class to Locate Elements

Searching for components on a page using their class name is a second method. An HTML tag’s class attribute contains the class name. A CSS class is intended to apply to a collection of DOM elements. The “.find_element_by_class_name()” method returns only the first element with the matching class. If there isn’t an element with the specified class name, it raises a NoSuchElementException. Here’s how you use the driver’s method:

from selenium import webdriver

driver = webdriver.Chrome(‘./chromedriver’)

driver.get(“https://www.python.org”)

# Returns first element with matching class

first_search_bar = driver.find_element_by_class_name(“id-class-name”)

Name to Locate Elements

Form components in HTML5 frequently have a name property attached to them. The “.find_element_by_name()” method returns only the first element with the matching class. The first element that matches will be returned if there are numerous elements with the same name. A NoSuchElementException fault occurs when there are no matching elements.

Consider the following example:

<form id=”loginForm”>

<input name=”name” type=”text” value=”First Name” />

<input name=”name” type=”text” value=”Last Name” />

<input name=”email” type=”text” value=”Business Email” />

<input name=”password” type=”password” />

<input name=”continue” type=”submit” value=”Sign Me Up” />

</form>

To retrieve the email form element, use the code that follows.

email_input = driver.find_element_by_name(“email”)

But the code that follows only gets back the first name of the element.

name_input = driver.find_element_by_name(“name”)

Reaching the last name input field in the sample is not possible with the ‘.find_element_by_name()’ technique. 

Explore the popular software testing jobs.

XPath to Locate Elements

If an element cannot be located using its XML path, it must be found using its ID, class, or name. It is also possible to use this procedure when reading an XML document. Since absolute routes can become incorrect with even the smallest alteration to the HTML structure, we will examine the use of relative paths in the next section.

To discover the right element on the page, we’ll utilize the ‘.find_element_by_xpath()’ method. The path to the element is the parameter that the ‘.find_element_by_xpath()’ function accepts.

Use the following code to locate the email input field in the HTML form example above:

email_input = driver.find_element_by_xpath(“//form[input/@name=’email’]”)

This code searches for the first form element on the page. This form narrows down to the necessary element by looking for the input with the name, which equals the value of the email.

Let’s now attempt to find the input element for the first and last names on the form above.

first_name = driver.find_element_by_xpath(“//form[@id=’loginForm’]/input[1]”)

last_name = driver.find_element_by_xpath(“//form[@id=’loginForm’]/input[2]”)

The first and second input elements of the form are chosen as the first and last names after the technique first looks for a form with the ID login form.

tagName to Locate Elements

Testers may want to investigate a few additional element locators in the Selenium WebDriver in addition to the well-known techniques we’ve covered.

The ‘.find_element_by_tag_name()’ method can be used to discover elements based on their HTML tag name.

page_heading = driver.find_element_by_tag_name(‘h1’)

linkText to Locate Elements

The link text can also be used to look for a hyperlink element. To find the precise link’s text, one can either utilize the ‘.find_element_by_link_text()’ method.

# Exact Link Text

click_here_link = driver.find_element_by_link_text(‘Click Here’)

partialLinkText to Locate Elements

Alternatively, one might use the incomplete link text to look for a hyperlink element. Use the ‘.find_element_by_partial_link_text()’ function to look for a section of a text.

# Partial Link Text 

click_here_link = driver.find_element_by_partial_link_text(‘Click’)

Discover what is the software testing salary here.

Locating Multiple Elements

These are some common scenarios when the ‘.find_elements()’ function is used. Use the following code to discover every input element on a form with an ID login form:

from selenium.webdriver.common.by import By

all_inputs = driver.find_elements(By.XPATH, ‘//form[@id=’loginForm’]/input’)

Use the code below to find all elements having a class name:

from selenium.webdriver.common.by import By

all_elements = driver.find_elements(By.CLASS_NAME, ‘my-css-class’)

Example for Locators in Selenium

The utilization of different Selenium locators to locate and search the page’s items is shown in the following code snippet:

package TestPackage;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class Selenium {

public static void main(String[] args) {

String exePath = “C:\\Selenium\\chromedriver\\chromedriver.exe”;

System.setProperty(“webdriver.chrome.driver”, exePath);

WebDriver driver = new ChromeDriver();

driver.get(“https:\\demoqa.com\\”);

/**Locate by ID Attribute

  * URL – https://demoqa.com/automation-practice-form

  */

driver.get(“https://demoqa.com/automation-practice-form”);

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

/**

  *  Locate by Name attribute

  *  URL – https://demoqa.com/automation-practice-form

  */

driver.get(“https://demoqa.com/automation-practice-form”);

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

/**

  *  Locate by className attribute

  *  URL – https://demoqa.com/automation-practice-form

  */

driver.get(“https://demoqa.com/automation-practice-form”);

driver.findElement(By.className(“practice-form-wrapper”));

/**

  *  Locate by linkText and ParticalLinkText attribute

  *  URL – https://demoqa.com/links

  */

driver.get(“https://demoqa.com/links”);

//linkText

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

//partialLinkText

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

/**

  *  Locate by tagName attribute

  *  URL – https://demoqa.com/links

  */

driver.get(“https://demoqa.com/links”);

List <WebElement> list = driver.findElements(By.tagName(“a”));

/**

  *  Locate by cssSelector attribute

  *  URL – https://demoqa.com/text-box

  */

driver.get(“https://demoqa.com/text-box”);

driver.findElement(By.cssSelector(“input[id= ‘userName’]”));

/**

  *  Locate by xpath attribute

  *  URL – https://demoqa.com/text-box

  */

driver.get(“https://demoqa.com/text-box”);

driver.findElement(By.xpath(“//input[@id=’userName’]”));

}

}

Best Practices for Locators in Selenium

In Selenium, selecting the appropriate location to identify a web element is crucial. Some best practices for utilizing locators in the Selenium WebDriver-based automation framework are provided below for quality engineers.

  • Dynamic attribute values should not be used to find elements since they may change often and cause the locator script to break. It also negatively impacts the automation script’s efficiency, dependability, and maintainability.
  • Identifiers and names are more important than other locators. It is usually recommended to use a unique ID and name on your web page rather than XPath since they are more effective and faster.
  • Make sure your locator points exactly to the needed element when utilizing one. Make sure your locator precisely matches only one element if the required scenario requires you to conduct some sort of action on a single element. The locator can crash your script if it points to multiple separate items. Enroll in our software testing training in Chennai at SLA Jobs to learn more about locators in Selenium.
  • Never utilize locators to find automatically created web page items. Run-time generation of element attribute properties occurs occasionally in dynamic web environments. These components should be avoided, as they could lead to script execution errors.
  • Although it can appear to be one of the simplest ways to create XPath, it eventually leads to problems with maintainability, code-breaking, and dependability. If you are using XPath or CSS locators, you should not use the locator generated by the Chrome Dev Tools directly. Although using these might seem appealing, in the long term, you would be better off making your own customized XPath.

Final Thoughts

  • Selenium supports eight different locator types: ID, class name, name attribute, XPath, tagName, linkText, partialLinkText, and tagName.
  • One of the fastest and most dependable ways to recognize elements is by using ID. On a particular webpage, the ID is often unique at all times.
  • Dynamic elements on a web page can be recognized using XPath and the CSS selector. 
  • An element can be recognized using a combination of its attributes and tag names when using CSS and XPath.

Finally, we now know how to use different locators in Selenium in a variety of ways. Explore a wide range of opportunities by equipping your skills through our Selenium training in Chennai at SLA Jobs.