Finding elements in selenium with Java

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:

  • id
  • className
  • xpath
  • tagName
  • name
  • linkText
  • partialLinkText
  • cssSelector

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”));

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x