Finding the right element is the foundation of every Selenium test. Selenium provides multiple locator strategies — choose the most stable one available.
Locator Strategies
from selenium.webdriver.common.by import By
# Preferred — fast and readable
driver.find_element(By.ID, "username")
driver.find_element(By.CSS_SELECTOR, "input[name='email']")
driver.find_element(By.CSS_SELECTOR, ".btn-primary")
# Useful for complex relationships
driver.find_element(By.XPATH, "//button[text()='Submit']")
driver.find_element(By.XPATH, "//label[text()='Name']/following-sibling::input")
# Avoid when possible — brittle
driver.find_element(By.CLASS_NAME, "submit") # fails if class changes
driver.find_element(By.TAG_NAME, "button") # matches ALL buttonsPrefer ID > CSS_SELECTOR > XPATH in that order of stability.
Common Interactions
from selenium.webdriver.common.keys import Keys
# Typing
field = driver.find_element(By.ID, "search")
field.clear()
field.send_keys("Selenium tutorial")
field.send_keys(Keys.RETURN) # press Enter
# Clicking
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
# Reading
el = driver.find_element(By.CSS_SELECTOR, "h1")
print(el.text) # visible text
print(el.get_attribute("data-id")) # HTML attribute
print(el.get_attribute("value")) # for inputs
# Checkbox / radio
checkbox = driver.find_element(By.ID, "agree")
if not checkbox.is_selected():
checkbox.click()
# Dropdown
from selenium.webdriver.support.ui import Select
sel = Select(driver.find_element(By.ID, "country"))
sel.select_by_visible_text("United Kingdom")Locator Practice Page
Locator practice
Ctrl+Enter
HTML
CSS
JS
Preview
Finding Multiple Elements
# Returns a list — empty list if nothing found (no exception)
items = driver.find_elements(By.CSS_SELECTOR, "ul.results li")
for item in items:
print(item.text)
# Check count
assert len(items) == 5, f"Expected 5 results, got {len(items)}"