Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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(">")).
-
Name − This attribute is not unique for every element.
Syntax − driver.findElement(By.name(">")).
-
CSS Selector − This can be derived from element tags and attributes.
Syntax −
driver.findElement(By.cssSelector(">")).
-
xpath − This can be derived from element tags and attributes.
Syntax −
driver.findElement(By.xpath(">")).
-
TagName − This can be derived from the HTML tags to identify the elements.
Syntax − driver.findElement(By.tagName(">")).
-
LinkText − This can be derived from the anchor text to identify the elementsz
Syntax − driver.findElement(By.linkText(">")).
-
PartialLinkText − This can be derived from the partial anchor text to identify the elements
Syntax − driver.findElement(By.partialLinkText(">")).
-
Classname − This can be derived from the class name attribute
Syntax − driver.findElement(By.className(">")).
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();
}
} 