Identifying Elements Using Different Locator Types in Selenium (Java)
Selenium provides multiple locator strategies to identify elements on a web page. Below are the different locator types available:
Locator Types:
idclassNamexpathtagNamenamelinkTextpartialLinkTextcssSelector
Usage of locator types:
Following are the examples of usage for different locator types in selenium with java
id:
Example to identify element based id below. Replace elementId with id in the web page as required
WebElement elem = driver.findElement(By.id(“elementId”));
className:
Example to identify element based name of the class below. Replace className with name of the class in the web page as required
WebElement elem = driver.findElement(By.className(“className”));
xpath:
xpath example to identify all the links in a web page below
List<WebElement> elem = driver.findElements(By.xpath(“//a”));
tagName:
tagName example to identify all the links in a web page below
List<WebElement> elem = driver.findElements(By.tagName(“//a”));
name:
Example to identify element based name property below. Replace elementName with name attribute value in the web page as required
WebElement elem = driver.findElement(By.name(“elementName”));
linkText:
linkText example to identify element based title of the link below. Replace elementText with title of the link in the web page as required
WebElement elem = driver.findElement(By.linkText(“elementText”));
partialLinkText:
partialLinkText example to identify element based partial title of the link below. Replace partialLinkTitle with matching title of the link text in the web page as required
WebElement elem = driver.findElement(By.partialLinkText(“partialLinkTitle”));
cssSelector
Example to identify element based css selector is below. Replace className with name of the class in the web page as required. Identifier for the class name is ‘.’.
WebElement elem = driver.findElement(By.cssSelector(“.className”));