UI Automation: Selenium + Playwright + pytest · Lesson 1 of 6

Selenium Locators: Finding the Element You Mean

Every UI test starts the same way: point at something on the page, then do something to it. This lesson is all about the pointing part. It's simpler than it looks.

By Shahriyar · Updated

The idea, in one line

A locator is your way of telling the browser which element you mean. Selenium reaches all of them through one class called By.

How you call it

Use driver.find_element(By.X, "value") for a single match. Use driver.find_elements(...) (note the s) for a list. If nothing matches, the list version just returns an empty list — it does not crash.

Selenium 4 gives you eight ways to point at an element:

See it work

▸ try it
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.saucedemo.com/")

# One element, found by its name attribute
driver.find_element(By.NAME, "user-name").send_keys("standard_user")
driver.find_element(By.NAME, "password").send_keys("secret_sauce")

# A CSS selector aimed at a stable test hook
driver.find_element(By.CSS_SELECTOR, "[data-test='login-button']").click()

# find_elements gives a list -> handy for counting
items = driver.find_elements(By.CLASS_NAME, "inventory_item")
print(len(items), "products listed")

driver.quit()

Read it top to bottom: open a browser, find each field, type into it, click login, then count the products. Every step begins by locating one element.

Advanced — pick locators that survive a redesign

Prefer stable, human-meaningful hooks. By.ID is best when it exists. By.CSS_SELECTOR handles most of the rest. Reach for By.XPATH only when you truly need it.

Grounded in the official Selenium (Python) docs — WebDriver Locators

All lessons in UI Automation: Selenium + Playwright + pytest

  1. Selenium Locators: Finding the Element You Mean
  2. Waits, Actions & Frames — Killing Flakiness at the Source
  3. Playwright: Auto-Waiting, Locators & Tracing
  4. pytest Deep-Dive: Fixtures, conftest, Parametrize & Markers
  5. Page Object Model, Done Properly
  6. The Hard Stuff: Dynamic Elements, iframes, Uploads & Network Stubbing