</>

Technology

Selenium

Difficulty

Beginner

Interview Question

What are various ways of locating an element in Selenium?

Selenium provides 8 locator strategies: id, name, className, tagName, linkText, partialLinkText, cssSelector, and xpath.

Answer

Selenium WebDriver provides 8 locator strategies:

LocatorExampleBest For
idBy.id("username")Fastest — unique ID
nameBy.name("email")Form fields with name attribute
classNameBy.className("btn")Elements with unique class
tagNameBy.tagName("input")Group of same-type elements
linkTextBy.linkText("Click Here")Exact anchor text
partialLinkTextBy.partialLinkText("Click")Partial anchor text
cssSelectorBy.cssSelector("#id .class")Fast, flexible selection
xpathBy.xpath("//input[@id=''user'']")Most powerful, DOM traversal

Priority order (fastest to slowest): id > name > cssSelector > xpath

Quick example:

Java
driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.cssSelector(".btn-primary")).click();
driver.findElement(By.xpath("//button[text()=''Submit'']")).click();

Follow AutomateQA

Related Topics