What is a Locator

Finding an Element

A locator tells Selenium how to find an element on the page. You pass a By object to driver.findElement() and get back a WebElement you can click or type into.

<form id="login-form">
  <input type="email" id="email" name="email" class="form-input" placeholder="Email">
  <input type="password" id="password" name="password" class="form-input">
  <button type="submit" id="login-btn" class="btn btn-primary">Login</button>
  <a href="/forgot-password">Forgot your password?</a>
</form>

The Eight Strategies

LocatorExample for the form above
By.idBy.id("email")
By.nameBy.name("password")
By.classNameBy.className("btn-primary")
By.tagNameBy.tagName("button")
By.linkTextBy.linkText("Forgot your password?")
By.partialLinkTextBy.partialLinkText("Forgot")
By.cssSelectorBy.cssSelector("#login-form .btn-primary")
By.xpathBy.xpath("//button[text()='Login']")