Skip to main content

Setup & First Test

Selenium WebDriver is the industry-standard library for controlling web browsers programmatically. You write Python (or Java, C#, etc.) code that drives a real browser — clicking buttons, filling forms, reading text — exactly as a user would.

Installation

pip install selenium

From Selenium 4.6+, you no longer need to manually download ChromeDriver. Selenium Manager handles it automatically.

Your First Test

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()          # opens Chrome
driver.get("https://example.com")   # navigates to URL

heading = driver.find_element(By.TAG_NAME, "h1")
print(heading.text)                  # "Example Domain"

driver.quit()                        # always close the browser

Browser Options

from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")   # run without a visible window
options.add_argument("--no-sandbox")
options.add_argument("--window-size=1920,1080")

driver = webdriver.Chrome(options=options)

Headless mode is essential for CI pipelines where there is no display.

The WebDriver Lifecycle

WebDriver lifecycle
Ctrl+Enter
HTML
CSS
JS
Preview

Running with pytest

# test_homepage.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

@pytest.fixture
def driver():
    d = webdriver.Chrome()
    yield d
    d.quit()          # teardown runs after every test

def test_title(driver):
    driver.get("https://example.com")
    assert "Example" in driver.title

def test_heading(driver):
    driver.get("https://example.com")
    h1 = driver.find_element(By.TAG_NAME, "h1")
    assert h1.text == "Example Domain"

Run with:

pytest test_homepage.py -v