1. Home
  2. Blog
  3. Test Automation

Test Automation

Selenium Python Tutorial for Beginners: Setup and Your First Test

This selenium python tutorial takes you from an empty folder to a working, pytest-powered browser test. Install, locate elements, wait properly and avoid the mistakes that make beginner scripts flaky.

9 min read
Selenium Python tutorial for beginners: setup, first test and pytest example

Key takeaways

  • Selenium 4 ships with Selenium Manager, so you no longer download ChromeDriver by hand.
  • Install with pip install selenium pytest inside a virtual environment.
  • Prefer explicit waits and stable locators over time.sleep().
  • Wrap the driver in a pytest fixture so every test gets a clean browser and always closes it.

You want to automate a browser with Python, but every guide seems to start with a different driver setup. This selenium python tutorial uses the current Selenium 4 workflow, where one pip command is enough to get going.

By the end you will have a small test suite that opens a real web form, fills it in, checks the result and runs from the command line. Every snippet was written against the official Selenium example page.

No automation background is needed. If Python itself is new to you, skim our Python tutorial for beginners first, then come back.

What you need before this Selenium Python tutorial

  • Python 3.10 or newer. The latest Selenium release on PyPI (4.52.0 when I checked) lists Python 3.10 as the minimum.
  • A browser such as Chrome, Firefox or Edge installed normally.
  • A code editor and a terminal.

Selenium itself is a browser automation library. Python only sends commands; the browser does the real work. A small program called a driver sits between them. Since Selenium 4.6, Selenium Manager finds or downloads the right driver for you.

Setup in five minutes

Every selenium python tutorial starts here, so keep this part boring and repeatable.

Create a project folder and a virtual environment so the packages stay isolated. Our Python virtual environment tutorial explains each step in detail.

mkdir selenium-demo && cd selenium-demo
python -m venv .venv
# Windows: .venv\Scripts\activate     macOS/Linux: source .venv/bin/activate
pip install selenium pytest
python -c "import selenium; print(selenium.__version__)"

If the last command prints a version number, the setup is done. There is no driver to download and no PATH to edit in a normal setup.

Your first script

Save this as first_test.py. It follows the pattern in the official Selenium getting started guide.

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

driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/web-form.html")

print(driver.title)                      # Web form

box = driver.find_element(By.NAME, "my-text")
button = driver.find_element(By.CSS_SELECTOR, "button")

box.send_keys("Selenium")
button.click()

message = driver.find_element(By.ID, "message")
print(message.text)                      # Received!

driver.quit()

Run it with python first_test.py. A browser window opens, the form is submitted and the script prints the page title and the confirmation text. Always end with driver.quit(), otherwise browser processes stay alive in the background.

Tip: Use webdriver.Firefox() or webdriver.Edge() to switch browsers. The rest of the script stays the same, which is the main reason teams choose Selenium.

Finding elements: locator strategies

Locators are the part of any selenium python tutorial that decides whether your tests survive next month’s redesign.

Every test depends on finding the right element. Selenium offers several strategies through the By class. Pick the most stable one you can.

Strategy Example When to use it
By.ID find_element(By.ID, "message") Best choice when the id is unique and stable
By.NAME find_element(By.NAME, "my-text") Form fields
By.CSS_SELECTOR find_element(By.CSS_SELECTOR, "form button") Flexible and fast; the everyday workhorse
By.XPATH find_element(By.XPATH, "//button[text()='Submit']") Text matching or walking up to a parent
By.LINK_TEXT find_element(By.LINK_TEXT, "Return to index") Links with fixed text

Use find_elements (plural) to get a list. It returns an empty list when nothing matches, while find_element raises NoSuchElementException. Avoid long absolute XPaths like /html/body/div[2]/div[1]/button; they break whenever the layout changes.

Waiting correctly

Pages load in pieces. If your script clicks before a button exists, you get an exception, so beginners add time.sleep(5). That makes tests slow and still unreliable. Use an explicit wait instead:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, timeout=10)
message = wait.until(EC.visibility_of_element_located((By.ID, "message")))
assert message.text == "Received!"

The wait polls until the condition is true and returns as soon as it is, up to ten seconds. The official waits documentation also covers implicit and fluent waits, and we compare all three in Selenium WebDriver waits explained. Do not mix implicit and explicit waits in the same suite, because the timings can add up in confusing ways.

Turn the script into a pytest test

This is the step most selenium python tutorial articles skip, yet it is what separates a demo from a real suite.

A script that prints is not a test. A test asserts something and reports pass or fail. pytest gives you that, plus fixtures that handle the browser lifecycle. Create conftest.py:

import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    options = webdriver.ChromeOptions()
    options.add_argument("--headless=new")   # remove to watch the browser
    d = webdriver.Chrome(options=options)
    yield d
    d.quit()

Now write test_form.py:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

URL = "https://www.selenium.dev/selenium/web/web-form.html"

def test_page_title(driver):
    driver.get(URL)
    assert driver.title == "Web form"

def test_submit_form(driver):
    driver.get(URL)
    driver.find_element(By.NAME, "my-text").send_keys("Selenium")
    driver.find_element(By.CSS_SELECTOR, "button").click()
    msg = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.ID, "message")))
    assert msg.text == "Received!"
pytest -v

The fixture starts a fresh browser for each test and always calls quit(), even when an assertion fails. That isolation is what keeps a growing suite stable.

Keep tests tidy with a page object

After this selenium python tutorial’s first tests pass, structure matters more than new features.

Once you have more than a few tests, move locators out of the test body. A page object is just a class that owns one page’s locators and actions.

class WebFormPage:
    URL = "https://www.selenium.dev/selenium/web/web-form.html"

    def __init__(self, driver):
        self.driver = driver

    def open(self):
        self.driver.get(self.URL)
        return self

    def submit_text(self, text):
        self.driver.find_element(By.NAME, "my-text").send_keys(text)
        self.driver.find_element(By.CSS_SELECTOR, "button").click()

When the button changes, you fix one line instead of twenty tests. If you are still choosing a tool, see our list of the best test automation tools in 2026 and the Playwright vs Cypress comparison.

Common mistakes in a Selenium Python tutorial project

  • Using sleep instead of waits. Replace every time.sleep() with an explicit wait.
  • Forgetting to quit the driver. Use a fixture so cleanup is automatic.
  • Copying browser-generated XPaths. They are brittle; write short CSS selectors.
  • Testing against shared data. Create the data each test needs.
  • Chasing old advice. Posts that pass a driver path to webdriver.Chrome() or call find_element_by_id target Selenium 3; the second form was removed in Selenium 4.

Final thoughts

A good selenium python tutorial project is small: one install command, one fixture, stable locators and explicit waits. Copy the files above, point them at your own app and add one test at a time. When the suite grows, add page objects and run it in CI.

Frequently asked questions

Is this selenium python tutorial suitable for beginners?

Yes. Python syntax is short, pip installs Selenium in one command and Selenium Manager handles the driver, so a first test takes minutes.

Do I still need to download ChromeDriver?

Normally no. Since Selenium 4.6 Selenium Manager locates or downloads a matching driver automatically.

Which Python version does Selenium need?

The current PyPI release lists Python 3.10 or newer. Check the project page for the exact requirement of the version you install.

Should I use pytest or unittest with Selenium?

Either works, but pytest fixtures make browser setup and cleanup shorter, and most teams prefer pytest.

Why does my Selenium test fail only sometimes?

Usually a timing problem. Replace sleeps with explicit waits and use stable locators instead of long XPaths.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →