Locators in Selenium WebDriver– Types with Examples

Automation testing in current software & IT sector is top trending technology getting used widely for software testing. And, Selenium is one such tool that lets us automate the whole process of manual testing & that we term as Automation Testing. And, in this article, you will learn “How to identify locators in Selenium” with every possible types & example.

What is Locator in Selenium?

Locator is basically an identifier that is used to identify each element on webpage. In other words, locator used to identify each element on webpage.

Locator is a critical part of automation script, using this locator your automation script can perform action either action is to set text in input field or click on them.

But, to have a good skill in finding locators strategy is quite important. Because, changes in HTML DOM & locators start causing failure of our automation script. So, selecting a locator efficiently is quite important while writing an automation script as it will reduce our automation script failure.

Selenium WebDriver provides 8 methods to identify Web elements on GUI page.

  • Id
  • Name
  • Tagname
  • Link text
  • Partial link text
  • Class name
  • Css selector
  • xpath

Selection of locator depends on application HTML Dom and nature of web element. Refer below for when and how to use above locators in automation script.

Pre-Requisite:

  • Selenium Project should be set up
  • Basic understanding of HTML DOM( Optional)

Types of Locator with Example in Selenium

Here are the samples of locators with of their examples:

  • By ID:

ID is one of the most popular locator which is widely used. It’s quite a faster and safest locator. It’s preferred when ID is not changing and also no duplicate id available on webpage.

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

As per W3C standards, it should be unique on webpage but still due to some specific requirement developer violated. But when ID changes on page refresh, or after time or due to new development then we avoid use of id. In below case of ID is not recommended.

  • By Link Text

Web Element can be identified as using link text. Link Text can be used to element which comes under <a> tag and with their visible text. In below example “REGISTER” text can be identified using link text as it is under <a> tag.

// Locator 2- Using LinkText -Click on REGISTER using link text
driver.findElement(By.linkText("REGISTER")).click();
  • Partial Link Text

When Visible text is not changing and long then we can identify using partial text. Using this locator we can identify using a partial text locator. This locator also works for an element which comes under tag. In below example “SIGN-ON” is within tag and we will click using partial link text.

//Locator 3- Using Partial Link Text- Click on SIGN-ON using partial link text"SIGN"
driver.findElement(By.partialLinkText("SIGN")).click();
  • By Name

Name is an HTML attribute that is used to send value on server via POST and GET request. This attribute can also be used to identify web elements on-page. In below example, input field First Name is identified using name. It’s also not used when a name is frequently changing.

// Locator 4- Using Name- Identify first name field using name locator
driver.findElement(By.name("firstName")).sendKeys("Thoughtcoders");
  • By CSS Selector

CSS Selector is one of the most frequently used locator in Selenium Automation script. CSS stands for Cascading Style sheet which is used for website presentation and layout. CSS selector can be used when id, name, class name, or other selectors not fulfilling our requirement.

Sample CSS syntax:

css=<#>
css=<.>
css=<[attribute=Value of attribute]>
css=<[attribute^=prefix of the string]>
css=<:><(text)>

As compared to XPath it’s relatively faster in nature so it’s preferred over XPath. Also it gives the flexibility to customize.

// locator 5- Using CSS Selector
driver.findElement(By.cssSelector("input[name='lastName']")).sendKeys("team");
  • By Tag Name

Tag is the HTML property which is used to categories section of HTML DOM. This property is also used to identify Web Locator. Examples of Tag:
a div, span, tr, td, table, Html, body, tbody etc..

In below example select tag used to store dropdown elements.

// Locator 6- Using Tag name
WebElement dropdowns= driver.findElement(By.tagName("select"));
Select select = new Select(dropdowns);
select.selectByVisibleText("ALGERIA ");
  • By Class Name

Class Name is the specific attribute which is used to identify element or group of elements. Class Name is usually used by javascript and CSS to perform certain actions. Fortunately, Selenium also provides a method to identify web elements using class name.
In below example footer area text identified using classname.

// Locator 7- Using Class Name
WebElement footer= driver.findElement(By.className("footer"));
  • By Xpath

At the end, most popular locator is xpath which extensively used in Automation. Xpath is generally two types, first one is absolute and second is relative xpath. Relative xpath gives huge flexibility to identify element in reference of other xpath, using siblings, parents and ancestor.

This flexibility make it popular choice for everyone.

Sample relative xpath:
//tagname[@attribute=value]
//*[text()=’’]
//Locator 5- Using xpath
driver.findElement(By.xpath("//input[@name='phone']")).sendKeys("9555902032");

Selenium Script to Identify Web Elements using Selenium Locators

Complete Code:

package seleniumLocators;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import java.util.concurrent.TimeUnit;
public class linkText {
public static void main(String [] args) throws InterruptedException {
WebDriverManager.chromedriver().version("81.0").setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://newtours.demoaut.com");
Thread.sleep(7500);

//Locator 1- Using Partial Link Text- Click on SIGN-ON using partial link text"SIGN"
driver.findElement(By.partialLinkText("SIGN")).click();

// Locator 2- Using LinkText -Click on REGISTER using link text
driver.findElement(By.linkText("REGISTER")).click();

// Locator 3- Using Name- Identify first name field using name locator
driver.findElement(By.name("firstName")).sendKeys("Thoughtcoders");

// locator 4- Using CSS Selector
driver.findElement(By.cssSelector("input[name='lastName']")).sendKeys("team");

//Locator 5- Using xpath
driver.findElement(By.xpath("//input[@name='phone']")).sendKeys("9555902032");

// Locator 6- Using Tag name
WebElement dropdowns= driver.findElement(By.tagName("select"));
Select select = new Select(dropdowns);
select.selectByVisibleText("ALGERIA ");

// Locator 7- Using Class Name
WebElement footer= driver.findElement(By.className("footer"));
System.out.println(footer.getText());

//Locator 8- Using id
driver.findElement(By.id("email")).sendKeys("thoughtcoders@gmail.com");
driver.findElement(By.name("register")).click();
driver.close();
}
}

Best Practices for Locators

Above tutorial helps you to identify web elements using different available methods. But still, we would like to share a few best practices which may help you while working on live project:

Avoid use of TagName as there are higher chances that availability of 2 or more similar element in HTML DOM. This cause failure of automation script.
Never use ID when it generated on run time.
Avoid use of numeric locators.
Analyze Application and identify locator which will not change even after new development. Use that locator in Automation Script.
Prefer Xpath if you have to identify elements with respect to other elements.

I hope this article helps you to identify Web Element using different available methods in selenium and also suggested best practices help you to minimize locator related challenges. Feel free to write

Subscribe to our Newsletter:

0 0 vote
Article Rating
close

Subscribe to our Newsletter:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Open chat
Feel free to contact