• Selenium Video Tutorials

Selenium WebDriver - Locator Strategies



Once an application is launched, the user interacts with the elements on the page like clicking a link/button, typing a text within an input box, selecting an option from the dropdown, and so on to create an automation test case. The first task is to identify the elements with help of its attributes. This identification can be done using the locators namely id, name, class name, xpath, css, tagname, link text, and partial link.

Id Locator

The id attribute for an element can be used for its identification. In Java, the method findElement(By.id("<value of id attribute>")) is used to locate an element with the value of the id attribute. Using this, the first element with the matching value of the attribute id should be identified. In case there is no element with the similar value of the id attribute, NoSuchElementException is thrown.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.id("id value”)); 

Let us see the html of the input box beside Name highlighted in the below image −

Selenium Locator Strategies 1

The edit box highlighted in the above image has an id attribute having the value name. Let us make an attempt to enter text Selenium into this edit box.

Example

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LocatorID {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
      
      // Opening the webpage where we will identify edit box enter text
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");
      
      // Identify the search box with id locator then enter text Selenium
      WebElement i = driver.findElement(By.id("name"));
      i.sendKeys("Selenium");
      
      // Get the value entered
      String text = i.getAttribute("value");
      System.out.println("Entered text is: " + text);
      
      // Close browser
      driver.quit();
   }
}

It will show the following output −

Entered text is: Selenium

Process finished with exit code 0

The output shows the message - Process with exit code 0 means that the above code executed successfully. Also, the value entered within the edit box (obtained from the getAttribute method) - Selenium was received in the console.

Name Locator

The name attribute for an element can be used for its identification. In Java, the method findElement(By.name("<value of name attribute>")) is used to locate an element with value of the name attribute. Using this, the first element with the matching value of the attribute name should be identified. In case there is no element with the similar value of the name attribute, NoSuchElementException is thrown.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.name("name value"));

Let us investigate the html code of the same input box as discussed before in the below image −

Selenium Locator Strategies 2

The edit box highlighted in the above image has a name attribute having value as name. Let us input the text Selenium into this edit box.

Example

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LocatorName {
   public static void main(String[] args) throws InterruptedException {
   
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

      // Opening the webpage where we will identify edit box enter text
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // Identify the search box with name locator to enter text
      WebElement i = driver.findElement(By.name("name"));
      i.sendKeys("Selenium");
      
      // Get the value entered
      String text = i.getAttribute("value");
      System.out.println("Entered text is: " + text);
      
      // Close browser
      driver.quit();
   }
}

It will show the following output −

Entered text is: Selenium 

The value entered within the edit box - Selenium got printed in the console.

Class Name Locator

The class name attribute for an element can be used for its identification. In Java, the method findElement(By.className("<value of class name attribute>")) is used to locate an element with value of the class name attribute. Using this, the first element with the matching value of the attribute class name is identified. In case there is no element with the similar value of the name attribute, NoSuchElementException is thrown.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.className("class name value")); 

Let us see the html code of Click Me highlighted in the below image −

Selenium Locator Strategies 3

It has a class name attribute with value as btn-primary. Click on that element after that we would get the You have done a dynamic click on the page.

Selenium Locator Strategies 4

Example

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LocatorClassName {
   public static void main(String[] args) throws InterruptedException {
   
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      // adding implicit wait of 20 secs
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
      
      // Opening the webpage where we will identify button to click
      driver.get("https://www.tutorialspoint.com/selenium/practice/buttons.php");

      // Identify button with class name to click
      WebElement i = driver.findElement(By.className("btn-primary"));
      i.click();

      // Get text after click
      WebElement e = driver.findElement(By.xpath("//*[@id='welcomeDiv']"));
      String text = e.getText();
      System.out.println("Text is: " + text);
      
      // Closing browser
      driver.quit();
   }
}

It will show the following output −

Text is: You have done a dynamic click

We had obtained the text after clicking the Click Me button with the message in the console - Text is: You have done a dynamic click.

TagName Locator

The tagname for an element can be used for its identification. In Java, the method findElement(By.tagName("<value of tagname>")) is used to locate an element with the value of the tagname. Using this, the first element with the matching value of the tagname is identified. In case there is no element with the similar value of the tagname, NoSuchElementException is thrown.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.tagName("tag name value"));

Let us get the html code of the input box beside the text Name as the below image −

Selenium Locator Strategies 5

The input box highlighted in the above image has the tagname as input. Let us make an attempt to enter the text Java in that input box.

Example

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LocatorTagName {
   public static void main(String[] args) throws InterruptedException {

      //Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      //adding implicit wait of 10 secs
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // launch a URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // Identify input box with tagname locator
      WebElement t = driver.findElement(By.tagName("input"));

      // then enter text
      t.sendKeys("Java");

      // Get the value entered
      String text = t.getAttribute("value");
      System.out.println("Entered text is: " + text);
      
      // Closing browser
      driver.quit();
   }
}

It will show the following output −

Entered text is: Java

The value entered within the edit box Java got printed in the console.

Link Text Locator

The link text for a link can be used for its identification. In Java, the method findElement(By.linkText("<value of link text>")) is used to locate a link with the value of the link text. Using this, the first element with the matching value of the link text is identified. In case there is no element with the similar value of the link text, NoSuchElementException is thrown. It is mostly used to locate links on a web page.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.linkText("value of link text"));

Let us see the html code of the link Created highlighted in the below image −

Selenium Locator Strategies 6

It has the link text value as Created. Let us click on it after that we would get the Link has responded with status 201 and status text Created on the page.

Selenium Locator Strategies 7

Example

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LocatorLinkText {
   public static void main(String[] args) throws InterruptedException {

      //Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      //adding implicit wait of 10 secs
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // launch a URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/links.php");

      // Identify link with tagname link text
      WebElement t = driver.findElement(By.linkText("Created"));

      // then click
      t.click();

      // Get the text
      WebElement e = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[1]"));
      String text = e.getText();
      System.out.println("Text is: " + text);
      
      // Close browser
      driver.quit();
   }
}

It will show the following output −

Text is: Link has responded with status 201 and status text Created

We had obtained the text after clicking the Created link with the message in the console - Link has responded with status 201 and status text Created.

Partial Link Text Locator

The partial link text for a link can be used for its identification. In Java, the method findElement(By.partialLinkText(“<value of partial link text>”)) is used to locate a link with the value of the partial link text. Using this, the first element with the matching value of the partial link text is identified. In case there is no element with the similar value of the partial link text, NoSuchElementException is thrown. It is mostly used to locate links on a web page.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.partialLinkText("partial link text value"));

Let us investigate the html code of the link Bad Request highlighted in the below image −

Selenium Locator Strategies 8

It has the link text value as Bad Request. Click on IT after which we would obtain the text Link has responded with status 400 and status text Bad Request on the page.

Selenium Locator Strategies 9

Example

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class LocatorPartialLinkText {
   public static void main(String[] args) throws InterruptedException {

      //Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      //adding implicit wait of 10 secs
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // launch a URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/links.php");

      // Identify link with tagname partial link text
      WebElement t = driver.findElement(By.partialLinkText("Bad"));

      // then click
      t.click();

      // Get the text
      WebElement e = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[4]"));
      String text = e.getText();
      System.out.println("Text is: " + text);
      
      // Closing browser
      driver.quit();
   }
}

It will show the following output −

Text is: Link has responded with status 400 and status text Bad Request

We had obtained the text after clicking the Bad Request link with the message in the console - Link has responded with status 400 and status text Bad Request.

CSS Locator

The css locator value for an element can be used for its identification. In Java, the method findElement(By.cssSelector("<value of css selector>")) is used to locate an element with value of the css selector. Using this, the first element with the matching value of the css selector is identified. In case there is no element with the similar value of the css selector, NoSuchElementException is thrown.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.cssSelector("value of css selector"));

Rules to Create CSS Expression

The rules to create a css expression are discussed below −

  • To identify the element with css, the expression should be tagname[attribute='value'].
  • We can also specifically use the id attribute to create a css expression. With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute].
  • With class, the format of css expression should be tagname.class. For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute].
  • If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n). Similarly, to identify the last child, the css expression should be ul.reading li:last-child.

For attributes whose values are dynamically changing, we can use ^= to locate an element whose attribute value starts with a particular text. For example, input[name^='qa'] Here, input is the tagname and the value of the name attribute starts with qa.

For attributes whose values are dynamically changing, we can use $ = to locate an element whose attribute value ends with a particular text. For example, input[class $ ='txt'] Here, input is the tagname and the value of the class attribute ends with txt.

For attributes whose values are dynamically changing, we can use *= to locate an element whose attribute value contains a specific sub-text. For example, input[name*='nam'] Here, input is the tagname and the value of the name attribute contains the sub-text nam.

Let us get the html code of the input box beside the Name label as given below −

Selenium Locator Strategies 10

The edit box highlighted in the above image has a name attribute having the value as name, the css expression should be input[name='name'].

Xpath Locator

The xpath locator value for an element can be used for its identification. In Java, the method findElement(By.xpath("<value of xpath>")) is used to locate an element with the value of the xpath. Using this, the first element with the matching value of the xpath is identified. In case there is no element with the similar value of the xpath, NoSuchElementException is thrown.

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.xpath("value of xpath”));

Rules to Create Xpath Expression

To locate the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath, they are relative and absolute. The absolute xpath starts with / symbol and begins from the root node up to the element to be located.

For example −

/html/body/div[1]/div[2]/div[1]/input

The relative xpath begins with // symbol and does not begin from the root node.

For example −

//img[@alt='TutorialsPoint']

Let us see the deep dive of the html code of the highlighted link - Home starting from the root.

Selenium Locator Strategies 11

The absolute xpath for this element is −

/html/body/main/div/div/div[2]/p[1]/a

The relative xpath for element Home is −

//a[@href='https://www.tutorialspoint.com/index.htm']

Xpath Functions

There are also functions available which help to frame relative xpath expressions.

text()

It is used to locate an element with the visible text on the web page. The xpath expression for the Home link is −

//*[text()='Home']

starts-with()

It is used to identify an element whose attribute value begins with a specific text. This function is normally used for attributes whose value changes on each page load.

Let us investigate the html of the link Moved

Selenium Locator Strategies 12

The xpath expression is −

//a[starts-with(@id, 'mov')].

Conclusion

This concludes our comprehensive take on the tutorial on Selenium WebDriver Locator Strategies. We’ve started with describing Id Locator, Name Locator, Class Name Locator, TagName Locator, Link Text Locator, Partial Link Text Locator, CSS Locator, Xpath Locator and examples illustrating how to use them along with Selenium. This equips you with in-depth knowledge of the Selenium WebDriver Locator Strategies. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.

Advertisements