Environment Setup
- Install a supported browser (Chrome, Firefox, Edge, Safari).
- Add the Python bindings:
pip install selenium - Download the matching driver executable:
- Chrome → chromedriver
- Firefox → geckodriver
- Edge → msedgedriver
- Safari → safaridriver (built-in)
Place the driver in a directory listed in your PATH, or keep it next to the Python interpreter.
Quick Start Session
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.implicitly_wait(10)
Browser Metadata
| Property / Method | Purpose |
|---|---|
driver.title |
Page title |
driver.current_url |
Current URL |
driver.page_source |
Raw HTML |
driver.current_window_handle |
Active tab ID |
driver.window_handles |
List of all tab IDs |
Navigation & Window Control
driver.get("https://example.com")
driver.refresh()
driver.back()
driver.forward()
driver.maximize_window()
driver.minimize_window()
driver.set_window_size(800, 600)
driver.fullscreen_window()
driver.close() # Close active tab
driver.quit() # Kill browser process
Working with Web Elements
Attributes
| Attirbute | Description |
|---|---|
element.tag_name |
HTML tag |
element.text |
Visible text |
element.get_attribute("href") |
Attribute value |
Actions
search_box = driver.find_element(By.ID, "q")
search_box.clear()
search_box.send_keys("selenium")
search_box.submit()
button = driver.find_element(By.CSS_SELECTOR, "button.primary")
button.click()
Locator Strategies
Use explicit waits for robustness:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
try:
elem = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.NAME, "username"))
)
except TimeoutException:
print("Element not found")
find_element raises NoSuchElementException when absent; find_elements returns an empty list.
Running Tests with pytest
pytest tests/test_login.py
pytest tests/ --html=report.html --self-contained-html
pytest automatically closes the browser when the process ends; call driver.quit() explicitly to avoid orpahned drivers.
Common Pitfalls
- StaleElementReferenceException: The DOM changed after the element was located. Re-query the element after navigation, refresh, or form submission.
- Timing issues: Use explicit waits instead of fixed
sleepcalls. - Driver mismatch: Ensure driver version matches browser version exactly.
# Safe pattern
def safe_click(driver, locator):
return WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(locator)
).click()