What are the various locators that Selenium supports?


The various types of locators that Selenium support are listed below −

  • ID − This attribute is unique for every element.

    Syntax − driver.findElement(By.id("<<id expression>>")).

  • Name − This attribute is not unique for every element.

    Syntax − driver.findElement(By.name("<<name expression>>")).

  • CSS Selector − This can be derived from element tags and attributes.

    Syntax

    driver.findElement(By.cssSelector("<<tagname[attribute=’value’]>>")).

  • xpath − This can be derived from element tags and attributes.

    Syntax

    driver.findElement(By.xpath("<<//tagname[@attribute=’value’]>>")).

  • TagName − This can be derived from the HTML tags to identify the elements.

    Syntax − driver.findElement(By.tagName("<<tagname>>")).

     
  • LinkText − This can be derived from the anchor text to identify the elementsz

    Syntax − driver.findElement(By.linkText("<<anchor text>>")).

  • PartialLinkText − This can be derived from the partial anchor text to identify the elements

    Syntax − driver.findElement(By.partialLinkText("<<partial anchor text>>")).

  • Classname − This can be derived from the class name attribute

    Syntax − driver.findElement(By.className("<<class name exp>>")).


Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class Locator {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // Identify with Id attribute
      driver.findElement(By.Id("gsc-i-id1")).click();
      // Identify with name attribute
      driver.findElement(By.name("search")).click();
      //Identify with css attribute driver.findElement(By.cssSelector("input[name=’search’]"))
      .click();
      //Identify with xpath attribute driver.findElement(By.xpath("//input[@name=’search’]"))
      .click();
      // Identify with class name attribute
      driver.findElement(By.className("gsc-input")).click();
      //Identify with link text attribute
      driver.findElement(By.linkText("Home")).click();
      //Identify with partial link text attribute
      driver.findElement(By.partialLinkText("Hom")).click();
      //Identify with tagname attribute
      driver.findElement(By.tagName("input")).click();
      driver.close();
   }
}

Updated on: 10-Jun-2020

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements