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
| Element | ID | Selenium Java | Playwright |
|---|---|---|---|
| Login Button | loginBtn | driver.findElement(By.id("loginBtn")) | page.locator('#loginBtn') |
| User ID Input | userId | driver.findElement(By.id("userId")) | page.locator('#userId') |
| Search Field | exploreSearch | driver.findElement(By.id("exploreSearch")) | page.locator('#exploreSearch') |
2. By Name
Form inputs
| Element | Name | Selenium Java | Playwright |
|---|---|---|---|
| Password | password | driver.findElement(By.name("password")) | page.locator('[name="password"]') |
| Guest Name | guestName | driver.findElement(By.name("guestName")) | page.locator('[name="guestName"]') |
3. By CSS Selector
Class-based and attribute selectors
| Element | CSS Selector | Selenium 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
| Element | XPath | When 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
| Element | data-testid | Playwright |
|---|---|---|
| Hotel card | hotel-card | page.getByTestId('hotel-card') |
| Flight row | flight-row-fb1 | page.getByTestId('flight-row-fb1') |
| Cancel modal | cancel-modal | page.getByTestId('cancel-modal') |
6. By Link Text
For anchor elements
| Link Text | Selenium 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