Locators in Selenium – Locate by ID, ClassName, Name, TagName, LinkText, PartialLinkText

HOME

In this tutorial, we will go through what are Locators and different type of locators in Selenium. The prerequisite of any automation tool is to locate the web elements on a web page. Buy WHY?

One of the example is that suppose you want to login to gmail using any automation tool. Therefore, in this case you need to enter your email or phone and click on Next button. Here, Email Textbox and Next button are web elements.

Web Elements can be anything link TextBox, CheckBox, Radio Buttons, Links, Dropdowns, Image, soon.

What is Locator?

Locator is unique address of any web element on web page.

Types of Locators in Selenium

In this tutorial, we will use http://www.facebook.com for showing the use of different locators

How to find web elements?

1)  Locating by ID – Find the input element with ID.

Syntax

driver.findElement(By.id(“email”))

 

2)  Locating by ClassName – Find the input element with name of class

Syntax 

driver.findElement(By.ClassName("inputtext"))

3)  Locating by TagName –  Find the input element with TagName

Syntax 

driver.findElement(By.tagName("select"))

4)  Locating by Name – Find the input element with matching name attribute.

Syntax 

driver.findElement(By.name("email"))

5)  Locating by Linktext –   Find the link element with matching visible text

Syntax

driver.findElement(By.linkText("Forgot account?"))

6)  Partial Link Text – Find the link element with partial matching visible text

Syntax

driver.findElement(By.partialLinkText("Forgot "))

7)  XPath – Full form of XPath is XML Path. It is used to locate a web element on a web page using HTML DOM structure 

Syntax

By.xpath("//tagname[@Attribute = ‘value’]")

//: select the current node.
tagname: name of the tag of a particular node.
@: to select attribute.
Attribute: name of the attribute of the node.
Value: value of the attribute

There are 2 types of Xpath:-

1) Absolute Path
2) Relative Path

Absolute Path – It is the direct way to find any element. But as name suggest, it needs to be absolute. Any change made in the path will fail the xpath, result tool will not be able to locate the we element on the page.

Syntax

driver.findElement(By.xpath("//*[@id='yDmH0d']/div/div/div[2]/div[2]/div/div/div/div/div/div/ form/content/section/div/content/div/div/div/div/div/input"))

Relative Path –Relative XPath begins from the current location and is prefixed with a “//”. It starts from the middle of the DOM structure. To know more about XPath, click here

Syntax

By.xpath("//input[@name='identifier']")

7)  CSS Selectors – CSS Selectors are string patterns used to identify an element based on a combination of HTML tag, id, class, and attributes. Locating by CSS Selector is more complicated than the previous methods, but it is the most common locating strategy of advanced Selenium users because it can access even those elements that have no ID or name. To know more about CSS, click here

Below is an example that shows how to use different locators. In this example, we have used Id, name, className, tagName, partialLinkText and LinkText locators.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Automation_Practice_Form {
      public static void main(String[] args) {
          System.setProperty("webdriver.gecko.driver",
                                             "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\drivers\\geckodriver-v0.27.0-win64\\geckodriver.exe");
 
            WebDriver driver = new FirefoxDriver();
            driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
            driver.get("https://opensource-demo.orangehrmlive.com/");
            driver.manage().window().maximize();

            // Locate link by partialLinkText
             String PartialLinkText_Text = driver.findElement(By.partialLinkText("Orange")).getText();
             System.out.println("Text of PartialLinkText Locator is ->" + PartialLinkText_Text);

             // Locate link by LinkText
             String LinkText_Text = driver.findElement(By.linkText("Forgot your password?")).getText();
             System.out.println("Text of LinkText Locator is ->" + LinkText_Text);
                        
             // Locate FirstName by name
             driver.findElement(By.name("txtUsername")).sendKeys("Admin");

             // Locate LastName by id
             driver.findElement(By.id("txtPassword")).sendKeys("admin123");

             // Locate options of DropDown by tagName
             List linkName = driver.findElements(By.tagName("a"));
             System.out.println("List of Links:");
             for (WebElement link : linkName) {
                    System.out.println(link.getText() + " - " +link.getAttribute("href"));
          }
       driver.close(); 
   } 
}

Output
Text of PartialLinkText Locator is ->OrangeHRM, Inc 
Text of LinkText Locator is ->Forgot your password? 
List of Links: 
Forgot your password? - https://opensource-demo.orangehrmlive.com/index.php/auth/requestPasswordResetCode 
OrangeHRM, Inc - http://www.orangehrm.com/ 
- http://www.linkedin.com/groups?home=&gid=891077 
 - http://www.facebook.com/OrangeHRM 
 - http://twitter.com/orangehrm 
 - http://www.youtube.com/orangehrm
Advertisement

7 thoughts on “Locators in Selenium – Locate by ID, ClassName, Name, TagName, LinkText, PartialLinkText

  1. Hi Vibha, your blogs are very informative. I have read all your blogs. Apart from Internet Explorer, Google Chrome and Firefox, selenium use any other driver too?

    Like

  2. Thanks Nishant. Yes, apart from IE, Chrome and Firefox, there are other drivers too in Selenium.SafariDriverOperaDriverAndroidDriverIPhoneDriverHtmlUnitDriverMicrosoftEdgeDriverGhostDriver -WebDriver Wire Protocol for PhantomJSios-driverSelendroid – For mobile TestingBlackberry 10QtWebDriver – WebDriver implementation for QtjBrowserDriver – Web browser driver compatible with the Selenium WebDriver spec – headless, WebKit-based, pure Java

    Like

  3. I have updated my blog for the syntax of Absolute Path. It looks like thisdriver.findElement(By.xpath(\”//*[@id='yDmH0d']/div/div/div[2]/div[2]/div/div/div/div/div/div/ form/content/section/div/content/div/div/div/div/div/input\”)

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s