ZetCode

Python Selenium

last modified November 19, 2026 Python 3.15

In this article we show how to automate a web browser in Python with Selenium. We use it to test and scrape a small local website.

Selenium

Selenium is a framework for automating web browsers. Its core is WebDriver, a W3C standard protocol through which a program controls a real browser: it opens pages, clicks, types, and reads the page content. Each browser has its own driver program: chromedriver for Chrome, geckodriver for Firefox, msedgedriver for Edge. Selenium has bindings for Python, Java, C#, Ruby, and JavaScript.

Since Selenium 4.6, drivers no longer have to be downloaded by hand. The bundled Selenium Manager finds the installed browser, downloads the matching driver into ~/.cache/selenium, and starts it. It can even download the browser if none is installed. The examples use Selenium 4.53 with Google Chrome 157 in headless mode, which runs the browser without a window.

$ pip install selenium pytest

Demo website

The examples work with a small website for a bookshop, stored in the site directory. This is the home page.

site/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Green Leaf Books</title>
</head>
<body>
<h1>Green Leaf Books</h1>
<p class="intro">Second-hand books on gardening and nature.</p>
<p class="intro">Open Monday to Saturday.</p>

<ul id="menu">
  <li><a href="books.html">Books</a></li>
  <li><a href="order.html">Order</a></li>
  <li><a href="news.html">News</a></li>
  <li><a href="contact.html">Contact</a></li>
</ul>
</body>
</html>

The other pages are books.html, order.html, and news.html; we show them in the sections that use them. The contact.html page is missing on purpose. We serve the site with the built-in HTTP server of Python, started in another terminal.

$ python -m http.server 8000 -d site

First script

The first script opens the home page and prints its title.

first_page.py
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

driver = webdriver.Chrome(options=options)
try:
    driver.get('http://localhost:8000/')
    print(driver.title)
    print(driver.current_url)
    print(driver.capabilities['browserName'])
finally:
    driver.quit()

The ChromeOptions object configures the browser; the --headless=new argument runs Chrome without a window. Creating webdriver.Chrome starts chromedriver and a new browser session. The get method loads a page and waits until it has loaded. The quit method closes the browser and ends the driver; it is in the finally clause, so no browser process is left running when the script fails. For Firefox, we would use webdriver.Firefox with FirefoxOptions and the -headless argument.

$ python first_page.py
Green Leaf Books
http://localhost:8000/
chrome

Finding elements

The find_element method returns the first element that matches a locator and find_elements returns a list of all matches. The locator strategy is given by a constant of the By class.

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

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/')

    heading = driver.find_element(By.TAG_NAME, 'h1')
    print(heading.text)

    for p in driver.find_elements(By.CLASS_NAME, 'intro'):
        print(p.text)

    links = driver.find_elements(By.CSS_SELECTOR, '#menu a')
    for link in links:
        print(f'{link.text:8} {link.get_attribute("href")}')

    order = driver.find_element(By.LINK_TEXT, 'Order')
    print(order.get_dom_attribute('href'))

    print(driver.find_elements(By.ID, 'footer'))

The driver is also a context manager that calls quit at the end of the with block, which is shorter than try/finally. We find elements by tag name, class name, CSS selector, and link text. The text property is the visible text of an element. The get_attribute method returns the href property, which the browser resolves to an absolute URL, while get_dom_attribute returns the attribute exactly as written in the HTML. When nothing matches, find_elements returns an empty list.

$ python find_elements.py
Green Leaf Books
Second-hand books on gardening and nature.
Open Monday to Saturday.
Books    http://localhost:8000/books.html
Order    http://localhost:8000/order.html
News     http://localhost:8000/news.html
Contact  http://localhost:8000/contact.html
order.html
[]

Missing elements and XPath

Unlike find_elements, the find_element method raises NoSuchElementException when no element matches.

no_element.py
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/')

    try:
        driver.find_element(By.ID, 'footer')
    except NoSuchElementException as e:
        print(type(e).__name__)
        print(e.msg.splitlines()[0])

    xpath = "//ul[@id='menu']//a[contains(@href, 'news')]"
    print(driver.find_element(By.XPATH, xpath).text)

The exception message comes from the browser; we print only its first line, because the rest is a long stack trace of chromedriver. The message also shows that Selenium translates By.ID to a CSS selector. The second part uses an XPath expression, which can select elements by conditions that CSS cannot express, here a link inside the menu whose href contains news.

$ python no_element.py
NoSuchElementException
no such element: Unable to locate element: {"method":"css selector","selector":"[id="footer"]"}
News

Scraping a table

Elements can be searched within other elements. This lets us read a table row by row. The books page has the following table.

site/books.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Books - Green Leaf Books</title>
<style>
body { font-family: sans-serif; margin: 2em; }
table { border-collapse: collapse; }
th, td { border: 1px solid #ccc; padding: 4px 10px; }
th { background: #e8f0e0; }
tr.sold { color: #999; text-decoration: line-through; }
</style>
</head>
<body>
<h1>Books</h1>
<table id="books">
  <thead>
    <tr><th>Title</th><th>Author</th><th>Price</th></tr>
  </thead>
  <tbody>
    <tr data-id="1"><td>The Wild Garden</td><td>William Robinson</td><td>12.50</td></tr>
    <tr data-id="2"><td>Silent Spring</td><td>Rachel Carson</td><td>9.90</td></tr>
    <tr data-id="3"><td>The Living Soil</td><td>Eve Balfour</td><td>14.00</td></tr>
    <tr data-id="4" class="sold"><td>Walden</td><td>Henry David Thoreau</td><td>7.20</td></tr>
  </tbody>
</table>
<p><a href="index.html">Home</a> <a href="news.html" target="_blank">News</a></p>
</body>
</html>

The fourth book is sold; its row has the sold class. The second link opens the news page in a new tab, which we use later.

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

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/books.html')

    table = driver.find_element(By.ID, 'books')
    headers = [th.text.lower() for th in table.find_elements(By.TAG_NAME, 'th')]

    books = []
    for row in table.find_elements(By.CSS_SELECTOR, 'tbody tr'):
        cells = [td.text for td in row.find_elements(By.TAG_NAME, 'td')]
        book = dict(zip(headers, cells))
        book['price'] = float(book['price'])
        book['id'] = int(row.get_dom_attribute('data-id'))
        book['sold'] = 'sold' in (row.get_dom_attribute('class') or '')
        books.append(book)

for book in books:
    print(book)
print('available:', sum(b['price'] for b in books if not b['sold']))

We take the column names from the header cells and zip them with the cells of each body row, which gives one dictionary per book. Calling find_elements on an element searches only inside it. The data-id and class attributes are read with get_dom_attribute, which returns None for a missing attribute, hence the or ''. The data are processed after the browser is closed.

$ python scrape_table.py
{'title': 'The Wild Garden', 'author': 'William Robinson', 'price': 12.5, 'id': 1, 'sold': False}
{'title': 'Silent Spring', 'author': 'Rachel Carson', 'price': 9.9, 'id': 2, 'sold': False}
{'title': 'The Living Soil', 'author': 'Eve Balfour', 'price': 14.0, 'id': 3, 'sold': False}
{'title': 'Walden', 'author': 'Henry David Thoreau', 'price': 7.2, 'id': 4, 'sold': True}
available: 36.4

Filling a form

Selenium types into inputs, selects options, and clicks buttons in the same way a user does. The order page has a form that is handled by JavaScript.

site/order.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Order - Green Leaf Books</title>
</head>
<body>
<h1>Order</h1>
<form id="order">
  <label>Name <input type="text" name="name" id="name" required></label>
  <label>Book
    <select name="book" id="book">
      <option value="1">The Wild Garden</option>
      <option value="2">Silent Spring</option>
      <option value="3">The Living Soil</option>
    </select>
  </label>
  <label>Copies <input type="number" name="copies" id="copies" value="1" min="1"></label>
  <label><input type="checkbox" name="gift" id="gift"> Gift wrap</label>
  <button type="submit">Send order</button>
</form>
<p id="result" hidden></p>
<script>
document.getElementById('order').addEventListener('submit', e => {
  e.preventDefault();
  const f = new FormData(e.target);
  const book = document.querySelector('#book option:checked').text;
  const gift = f.get('gift') ? ' (gift wrapped)' : '';
  const msg = document.getElementById('result');
  msg.textContent = `Thank you, ${f.get('name')}: ${f.get('copies')} x ${book}${gift}`;
  msg.hidden = false;
});
</script>
</body>
</html>

When the form is submitted, the script shows a confirmation in the hidden result paragraph.

fill_form.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/order.html')

    driver.find_element(By.ID, 'name').send_keys('Alice')

    book = Select(driver.find_element(By.ID, 'book'))
    print([o.text for o in book.options])
    book.select_by_visible_text('Silent Spring')

    copies = driver.find_element(By.ID, 'copies')
    copies.clear()
    copies.send_keys('3')

    gift = driver.find_element(By.ID, 'gift')
    gift.click()
    print('gift selected:', gift.is_selected())

    result = driver.find_element(By.ID, 'result')
    print('result visible:', result.is_displayed())

    driver.find_element(By.CSS_SELECTOR, 'button[type=submit]').click()
    print('result visible:', result.is_displayed())
    print(result.text)

The send_keys method types text into an input. The Select class wraps a select element; it lists the options and selects one by visible text, value, or index. The copies field already contains 1, so we clear it first. Clicking the checkbox selects it. The is_displayed method shows that the result paragraph is hidden before the submit and visible after it.

$ python fill_form.py
['The Wild Garden', 'Silent Spring', 'The Living Soil']
gift selected: True
result visible: False
result visible: True
Thank you, Alice: 3 x Silent Spring (gift wrapped)

Waiting for content

Many pages load content after the page itself has loaded. The news page shows its items after 1.5 seconds and also has buttons that open dialogs.

site/news.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>News - Green Leaf Books</title>
</head>
<body>
<h1>News</h1>
<p id="status">Loading...</p>
<ul id="news"></ul>
<button id="subscribe">Subscribe</button>
<button id="leave">Leave</button>
<button id="ask">Your name</button>
<p id="answer"></p>
<script>
setTimeout(() => {
  const items = ['New books every Monday', 'Summer sale in July', 'Reading club on Fridays'];
  const ul = document.getElementById('news');
  for (const text of items) {
    const li = document.createElement('li');
    li.textContent = text;
    ul.append(li);
  }
  document.getElementById('status').textContent = 'Loaded 3 items';
}, 1500);
const answer = document.getElementById('answer');
document.getElementById('subscribe').onclick = () => alert('Subscribed!');
document.getElementById('leave').onclick = () => {
  answer.textContent = confirm('Really leave?') ? 'left' : 'stayed';
};
document.getElementById('ask').onclick = () => {
  answer.textContent = 'Hello, ' + prompt('What is your name?');
};
</script>
</body>
</html>

Reading the list right after get finds nothing. Instead of time.sleep, which waits too long or not long enough, we use an explicit wait.

waits.py
import time

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/news.html')
    print('at once:', len(driver.find_elements(By.CSS_SELECTOR, '#news li')))

    start = time.monotonic()
    wait = WebDriverWait(driver, timeout=5)
    wait.until(EC.text_to_be_present_in_element((By.ID, 'status'), 'Loaded'))
    print(f'waited {time.monotonic() - start:.1f} s')

    for li in driver.find_elements(By.CSS_SELECTOR, '#news li'):
        print(li.text)

    try:
        WebDriverWait(driver, 1).until(
            EC.presence_of_element_located((By.ID, 'comments')))
    except TimeoutException:
        print('no comments after 1 s')

WebDriverWait checks a condition repeatedly (every half second by default) until it is true or the timeout expires. The expected_conditions module has ready-made conditions; here we wait until the status text contains Loaded, which happens after about 1.5 seconds. When the timeout expires, until raises TimeoutException. Selenium also has implicit waits (driver.implicitly_wait), but the documentation advises not to mix them with explicit waits.

$ python waits.py
at once: 0
waited 1.5 s
New books every Monday
Summer sale in July
Reading club on Fridays
no comments after 1 s

Alerts, confirms, and prompts

JavaScript dialogs are not part of the page, so they cannot be found with find_element. Selenium handles them through the Alert object.

alerts.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/news.html')
    wait = WebDriverWait(driver, 3)
    answer = driver.find_element(By.ID, 'answer')

    driver.find_element(By.ID, 'subscribe').click()
    alert = wait.until(EC.alert_is_present())
    print('alert:', alert.text)
    alert.accept()

    driver.find_element(By.ID, 'leave').click()
    confirm = wait.until(EC.alert_is_present())
    print('confirm:', confirm.text)
    confirm.dismiss()
    print(answer.text)

    driver.find_element(By.ID, 'ask').click()
    prompt = wait.until(EC.alert_is_present())
    prompt.send_keys('Bob')
    prompt.accept()
    print(answer.text)

The alert_is_present condition waits for a dialog and returns it. The accept method presses OK and dismiss presses Cancel, so confirm returns false and the page writes stayed. For a prompt, send_keys types the answer before it is accepted.

$ python alerts.py
alert: Subscribed!
confirm: Really leave?
stayed
Hello, Bob

Running JavaScript

The execute_script method runs JavaScript in the page and returns its result converted to Python values.

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

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/books.html')

    print(driver.execute_script('return document.title'))
    print(driver.execute_script('return navigator.userAgent.includes("Headless")'))

    prices = driver.execute_script('''
        return [...document.querySelectorAll('#books tbody tr')]
            .map(row => Number(row.cells[2].textContent));
    ''')
    print(prices, type(prices))

    row = driver.find_element(By.CSS_SELECTOR, 'tr.sold')
    driver.execute_script('arguments[0].remove()', row)
    print(len(driver.find_elements(By.CSS_SELECTOR, '#books tbody tr')))

Strings, numbers, booleans, arrays, and objects come back as Python strings, numbers, booleans, lists, and dictionaries. The user agent of headless Chrome contains HeadlessChrome, which some sites use to detect automation. Elements can be passed to the script; they arrive in the arguments array. Here we remove the sold row from the table.

$ python run_script.py
Books - Green Leaf Books
True
[12.5, 9.9, 14, 7.2] <class 'list'>
3

Screenshots

The save_screenshot method saves the visible part of the page as a PNG image; the screenshot method of an element saves only that element.

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

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
options.add_argument('--window-size=800,400')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/books.html')
    print(driver.get_window_size())

    driver.save_screenshot('books.png')

    table = driver.find_element(By.ID, 'books')
    table.screenshot('table.png')
    print(table.size)

In headless mode, the window size is set with the --window-size argument. The size includes the browser frame, so the page area in the screenshot is somewhat smaller and the page gets a scrollbar. The element screenshot has the size of the table, which we get from the size property. The first image is shown below.

Screenshot of the books page
Figure: Screenshot of the books page
$ python screenshot.py
{'width': 800, 'height': 400}
{'height': 136, 'width': 377}

Navigation and windows

The driver keeps a browser history and can control several windows or tabs, each identified by a handle.

windows.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    driver.get('http://localhost:8000/')
    driver.find_element(By.LINK_TEXT, 'Books').click()
    print(driver.title)
    driver.back()
    print(driver.title)
    driver.forward()

    original = driver.current_window_handle
    driver.find_element(By.CSS_SELECTOR, 'a[target=_blank]').click()
    WebDriverWait(driver, 3).until(EC.number_of_windows_to_be(2))
    print(len(driver.window_handles), 'windows')

    new = [h for h in driver.window_handles if h != original][0]
    driver.switch_to.window(new)
    print('new tab:', driver.title)
    driver.close()

    driver.switch_to.window(original)
    print('back in:', driver.title)

After a click on the Books link, back returns to the home page and forward goes to the books page again. The link with target=_blank opens a new tab, but the driver stays in the original one. We wait until there are two windows, find the new handle, and switch to it with switch_to.window. The close method closes only the current tab; after it we must switch back.

$ python windows.py
Books - Green Leaf Books
Green Leaf Books
2 windows
new tab: News - Green Leaf Books
back in: Books - Green Leaf Books

Testing with pytest

Selenium is often used for end-to-end tests. With pytest, the browser is created in a fixture and shared by the tests.

test_shop.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

BASE = 'http://localhost:8000'

@pytest.fixture(scope='module')
def driver():
    options = webdriver.ChromeOptions()
    options.add_argument('--headless=new')
    driver = webdriver.Chrome(options=options)
    yield driver
    driver.quit()

def test_title(driver):
    driver.get(f'{BASE}/')
    assert driver.title == 'Green Leaf Books'

@pytest.mark.parametrize('page', ['books', 'order', 'news'])
def test_heading(driver, page):
    driver.get(f'{BASE}/{page}.html')
    assert driver.find_element(By.TAG_NAME, 'h1').text == page.title()

def test_order(driver):
    driver.get(f'{BASE}/order.html')
    driver.find_element(By.ID, 'name').send_keys('Alice')
    driver.find_element(By.CSS_SELECTOR, 'button[type=submit]').click()
    result = driver.find_element(By.ID, 'result')
    assert result.text == 'Thank you, Alice: 1 x The Wild Garden'

def test_news_loaded(driver):
    driver.get(f'{BASE}/news.html')
    WebDriverWait(driver, 5).until(
        EC.text_to_be_present_in_element((By.ID, 'status'), 'Loaded'))
    items = driver.find_elements(By.CSS_SELECTOR, '#news li')
    assert len(items) == 3

The fixture has the module scope, so one browser serves all tests of the file; the code after yield closes it at the end. The parametrize decorator runs the heading test for three pages. Starting a browser is slow, so sharing it makes the tests much faster, but the tests must not depend on the state left by each other; every test loads its page first. More about pytest is in the Python pytest article.

$ python -m pytest -v test_shop.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
collecting ... collected 6 items

test_shop.py::test_title PASSED                                          [ 16%]
test_shop.py::test_heading[books] PASSED                                 [ 33%]
test_shop.py::test_heading[order] PASSED                                 [ 50%]
test_shop.py::test_heading[news] PASSED                                  [ 66%]
test_shop.py::test_order PASSED                                          [ 83%]
test_shop.py::test_news_loaded PASSED                                    [100%]

============================== 6 passed in 2.97s ===============================

Finding broken links

The last program crawls the site and reports broken links. It visits every page reachable from the home page and checks the HTTP status of each.

check_links.py
from collections import deque
from urllib.parse import urljoin, urldefrag

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

START = 'http://localhost:8000/'

def page_links(driver):
    links = driver.find_elements(By.TAG_NAME, 'a')
    return [urldefrag(a.get_attribute('href')).url for a in links]

def crawl(driver, start):
    seen, broken = {start}, []
    queue = deque([(start, None)])

    while queue:
        url, parent = queue.popleft()
        driver.get(url)
        status = driver.execute_script(
            "return performance.getEntriesByType('navigation')[0].responseStatus")
        print(f'{status} {url.removeprefix(start) or "/"}')
        if status >= 400:
            broken.append((url, parent))
            continue
        for link in page_links(driver):
            if link.startswith(start) and link not in seen:
                seen.add(link)
                queue.append((link, url))
    return broken

options = webdriver.ChromeOptions()
options.add_argument('--headless=new')

with webdriver.Chrome(options=options) as driver:
    broken = crawl(driver, START)

for url, parent in broken:
    print(f'broken: {url} (linked from {parent})')

WebDriver does not expose the HTTP status of a page, but the browser does: the Navigation Timing API returns it in responseStatus. The crawler is a breadth-first search with a queue and a set of seen URLs; it remembers the page that linked to each URL so the report says where the broken link is. Only links on the same site are followed, and urldefrag removes #fragment parts. The home page is visited twice, as / and as index.html, because the URLs differ.

$ python check_links.py
200 /
200 books.html
200 order.html
200 news.html
404 contact.html
200 index.html
broken: http://localhost:8000/contact.html (linked from http://localhost:8000/)

Source

Selenium documentation

Selenium Python API

In this article we have automated a browser with Selenium. See also Python Playwright, a newer browser automation library, Python pytest, Python BeautifulSoup, and Python web scraping.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.