Skip to main content
← TesterRank/Automation Cheatsheet
Cheatsheets

Locators Cheatsheet

Find elements by ID, Name, CSS, XPath, data-testid, and Link Text. Every example uses TesterRank practice portals.

1. By ID

#id in CSS, By.id() in Selenium

ElementIDSelenium JavaPlaywright
Login ButtonloginBtn
driver.findElement(By.id("loginBtn"))
page.locator('#loginBtn')
User ID InputuserId
driver.findElement(By.id("userId"))
page.locator('#userId')
Search FieldexploreSearch
driver.findElement(By.id("exploreSearch"))
page.locator('#exploreSearch')

2. By Name

Form inputs

ElementNameSelenium JavaPlaywright
Passwordpassword
driver.findElement(By.name("password"))
page.locator('[name="password"]')
Guest NameguestName
driver.findElement(By.name("guestName"))
page.locator('[name="guestName"]')

3. By CSS Selector

Class-based and attribute selectors

ElementCSS SelectorSelenium Java
All "Add to Cart" buttons.add-to-cart-btn
driver.findElements(By.cssSelector(".add-to-cart-btn"))
Cancel booking buttons.cancel-booking
driver.findElements(By.cssSelector(".cancel-booking"))
Room select buttons.select-room-btn
driver.findElements(By.cssSelector(".select-room-btn"))

4. By XPath

For complex element relationships

ElementXPathWhen to Use
Button by text
//button[text()='Login']
When no ID/name available
Input by label
//label[text()='Email']/following-sibling::input
Complex form layouts
Row by content
//td[text()='Rajesh Kumar']/parent::tr
Find table row by cell value
Partial text
//a[contains(text(),'Dashboard')]
Links with dynamic text

5. By data-testid

Most reliable — designed for testing

Elementdata-testidPlaywright
Hotel cardhotel-card
page.getByTestId('hotel-card')
Flight rowflight-row-fb1
page.getByTestId('flight-row-fb1')
Cancel modalcancel-modal
page.getByTestId('cancel-modal')

6. By Link Text

For anchor elements

Link TextSelenium Java
"Home"
driver.findElement(By.linkText("Home"))
"My Bookings"
driver.findElement(By.linkText("My Bookings"))

7. Best Practices

  • Prefer data-testid — stable, won't change with redesigns
  • Use id when available — fastest, most reliable
  • Avoid XPath when CSS works — XPath is slower
  • Never use auto-generated class names (Tailwind is fine)
  • Use relative locators when elements don't have unique attributes