Selenium WebDriver Tutorial for Beginners: Build Your First Python Test

Selenium WebDriver Tutorial

Selenium WebDriver Tutorial for beginners should go beyond simply opening Chrome and clicking a button. A real Selenium test should interact with the application, handle dynamic behavior correctly, and verify that the expected result occurred.

In this tutorial, you will set up Selenium WebDriver with Python, use locators and waits, add assertions, and turn a simple browser script into a basic pytest test.

What Is Selenium WebDriver? A Selenium WebDriver Tutorial Overview

Selenium WebDriver is a browser automation technology that lets code control browsers.

It can open web pages, locate elements, enter text, click buttons, read page content, and perform many interactions a real user performs in a browser. WebDriver can run locally or remotely and provides a standardized interface for browser automation.

Selenium vs Selenium WebDriver

The terms are related but not identical.
Selenium is the broader browser-automation project and ecosystem. Selenium WebDriver is the main API used by languages such as Python, Java, C#, and JavaScript to control browsers.

For a beginner learning web automation, WebDriver is the part of Selenium you will work with most.

How Selenium WebDriver Works

A simplified workflow looks like:
Python test -> Selenium WebDriver -> Browser -> Web application

Your Python code sends commands through Selenium, and the browser performs those actions.

A test might:

  • Open a page.
  • Locate an input.
  • Enter test data.
  • Click Submit.
  • Wait for the result.
  • Verify that the expected result appears.

That final verification is important. Opening pages and clicking buttons is automation. Checking whether the expected behavior occurred turns those actions into a test.

What You Need Before Starting

  • A currently supported Python 3 version
  • Chrome or another supported browser
  • A code editor or IDE
  • Terminal or command prompt
  • Basic Python knowledge

You normally do not need to manually download ChromeDriver for a standard current Selenium setup.

Selenium WebDriver Tutorial: Install Selenium with Python

Install Selenium with:

Pip install selenium

For larger projects, using a Python virtual environment is also useful because it isolates project dependencies.

Do You Need to Download ChromeDriver Manually?

Many older tutorials tell you to manually download ChromeDriver, match it with your Chrome version, and add it to your system PATH.
Modern Selenium usually handles this differently. Selenium includes Selenium Manager, which can automatically manage the required browser driver when one has not already been provided.

A typical beginner setup can therefore be:
from selenium import webdriver
driver = webdriver.Chrome()

Manual configuration is still possible for environments that require it, but it is no longer the best default setup for beginners.

Selenium WebDriver Tutorial: Write Your First Test

Selenium provides a sample web form that can be used for practice.

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”
)

text_box = driver.find_element(By.NAME, “my-text”)
submit_button = driver.find_element(
    By.CSS_SELECTOR, “button”
)

text_box.send_keys(“Selenium”)
submit_button.click()

message = driver.find_element(By.ID, “message”)

assert message.text == “Received!”

driver.quit()

This simple test:

  • starts Chrome
  • opens the page
  • finds an input
  • enters text
  • submits the form
  • reads the result
  • verifies the expected message
  • closes the browser

The key line is:

assert message.text == “Received!”

Without the assertion, Selenium performs actions. With the assertion, the code verifies behavior.

Always Close the Browser

Use:

driver.quit()

when execution finishes. This ends the WebDriver session and closes the associated browser windows.

Find Elements with Selenium Locators

Before Selenium can interact with an element, it must locate it in the page.

LocatorPython
IDBy.ID
NameBy.NAME
CSS SelectorBy.CSS_SELECTOR
XPathBy.XPATH
Link TextBy.LINK_TEXT

How to Choose a Good Locator

Prefer locators that are: unique, stable, understandable and minimally dependent on the page layout

For example:

driver.find_element(By.ID, “email”)

is usually preferable to an absolute XPath such as:

/html/body/div[2]/div/form/div[3]/input

The absolute XPath depends heavily on the exact HTML structure. A small layout change can break it even when the actual field has not changed.

CSS selectors and XPath are both useful. The important factor is stability, not declaring one strategy universally superior.

Replacing a Fragile XPath with a Stable Locator

While working on a Selenium test for a login form, I initially used an absolute XPath to locate the email field:

driver.find_element(
By.XPATH,
“/html/body/div[2]/div/form/div[3]/input”
)

The test worked initially, but it started failing after the page layout was updated. The email field was still present, but the surrounding <div> structure had changed, which made the XPath invalid.

I inspected the updated HTML and found that the email field had a stable id attribute. I replaced the absolute XPath with:

driver.find_element(By.ID, “email”)

After the change, the test no longer depended on the position of the element in the page structure. This made the locator more stable and reduced failures caused by unrelated layout changes.

Interact with Web Elements

Enter Text

element.send_keys(“test data”)

Click an Element

element.click()

Read Visible Text

text = element.text

Read an Attribute

value = element.get_attribute(“value”)

The difficult part in modern applications is often not the action itself, but knowing when the element is ready.

Selenium Waits and Dynamic Pages

Web applications frequently load or update content through JavaScript. In a Selenium WebDriver Tutorial, understanding waits is essential because dynamic pages can change before Selenium interacts with an element. Selenium may therefore reach an element before the application is ready for the next interaction.
Poor synchronization is a common reason flaky tests occur when working with dynamic pages.

Fixed Sleeps

You could write:

import time
time.sleep(5)

but the test always waits five seconds. If the element appears after one second, time is wasted. If it appears after six seconds, the test may still fail.

Fixed sleeps can help during debugging but are usually weak as a long-term synchronization strategy.

Implicit Wait

An implicit wait affects element-location attempts globally.

driver.implicitly_wait(5)

Explicit Wait

An explicit wait targets a specific condition.

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

message = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located(
        (By.ID, “message”)
    )
)

This waits until the element reaches the required state or the timeout expires.

Do Not Casually Mix Wait Strategies

Mixing implicit and explicit waits can create confusing timeout behavior.

For dynamic interactions, explicit waits are often easier to understand because the test clearly states the condition it needs.

Fixing a Flaky Test Caused by Poor Synchronization

While testing a page with dynamically loaded content, I had a Selenium test that sometimes failed when trying to click a button immediately after the page loaded. The button was present in the DOM, but it was not yet visible and ready for interaction because the page was still loading the required data.

Initially, the test used a fixed sleep:

time.sleep(3)
driver.find_element(By.ID, “submit”).click()

The test was unreliable because the button could take different amounts of time to become ready.

I replaced the fixed delay with an explicit wait that checked for the required condition:

button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, “submit”))
)

button.click()

After this change, Selenium waited only until the button was actually ready instead of waiting for an arbitrary amount of time. This removed the intermittent failure and made the test more reliable.

Add Assertions to Selenium Tests

A Selenium WebDriver Tutorial should also explain how automated tests verify expected behavior through assertions.

Page Title

assert “Dashboard” in driver.title

Element Text

assert message.text == “Success”

Current URL

assert “/dashboard” in driver.current_url

Assertions should represent meaningful expectations. Adding more assertions does not automatically create a better test.

Turn the Script into a pytest Test

As a Selenium WebDriver Tutorial progresses, a test framework makes execution and organization easier.

A simple pytest test might be:

def test_form_submission(driver):
    driver.get(
        “https://www.selenium.dev/selenium/web/web-form.html”
    )

    text_box = driver.find_element(
        By.NAME, “my-text”
    )

    text_box.send_keys(“Selenium”)

    driver.find_element(
        By.CSS_SELECTOR, “button”
    ).click()

    message = driver.find_element(
        By.ID, “message”
    )

    assert message.text == “Received!”

Browser Setup and Cleanup With a Fixture

import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

The fixture creates the browser before the test and closes it afterward. This removes repeated setup and cleanup code as the test suite grows.

Common Selenium WebDriver Errors

NoSuchElementException

Possible causes:

  • incorrect locator
  • element has not loaded
  • page structure changed
  • element exists inside another context such as an iframe

Do not immediately increase the timeout without checking the real cause.

TimeoutException

A wait condition did not become true before the configured timeout.

Check the locator, expected condition, application state, and whether the expected behavior actually occurred.

StaleElementReferenceException

A stored WebElement can become stale when the DOM changes.

For example, a component may re-render after an API response. The previous WebElement then refers to something that no longer exists in the current DOM.

Locate the required element again after the page changes.

Element Not Interactable

Possible causes include:

  • element is hidden
  • another element overlays it
  • the wrong element was found
  • the element is not ready

Browser Startup Problems

Investigate:

  • browser installation
  • system restrictions
  • Selenium Manager connectivity
  • environment configuration
  • custom browser/driver settings

Do not assume every startup error is automatically a ChromeDriver-version problem.

Selenium Best Practices for Beginners

Build these habits early:

  • prefer stable locators
  • avoid unnecessary fixed sleeps
  • wait for meaningful conditions
  • keep tests independent
  • give tests clear names
  • clean up browser sessions
  • write specific assertions
  • reduce duplicated interactions
  • use test data intentionally
  • understand failures before adding retries

Retries can hide unstable tests rather than solve the underlying problem.

What Is Page Object Model?

As a Selenium test suite grows, tests often repeat the same locators and page interactions.
A Page Object groups those page-specific elements and actions into reusable code.

For example, instead of putting username, password, and login-button locators inside every test, a LoginPage can contain those details once.
Page Objects can improve maintainability. However, beginners should understand normal WebDriver tests before building a large framework around them.

Cross-Browser Testing with Selenium

Selenium can create sessions for different browsers.

webdriver.Chrome()
webdriver.Firefox()
webdriver.Edge()

This does not mean every browser will automatically behave identically.
Real cross-browser testing still requires deliberate environment and coverage decisions. For larger remote or parallel execution needs, Selenium Grid can be introduced later.

Selenium WebDriver vs Playwright and Cypress

ToolGeneral Fit
SeleniumMature, flexible, multi-language automation
PlaywrightIntegrated modern cross-browser testing
CypressJS/TS-focused web testing workflow

There is no universal winner.
Choose according to browser requirements, programming language, existing technology, team skills, and maintenance needs.

For a detailed comparison, see our Software Testing Tools guide.

Is Selenium WebDriver Still Worth Learning?

Selenium remains useful for teams and projects that already use Selenium-based automation. For beginners, this Selenium WebDriver Tutorial provides a foundation for learning browser automation, locator design, synchronization, assertions, and test structure.

It also teaches transferable browser-testing skills such as:

  • locator design
  • synchronization
  • assertions
  • debugging
  • test structure
  • cross-browser thinking

For new projects, Selenium should still be evaluated against appropriate alternatives rather than selected automatically.

The transferable skill is understanding browser automation and test design, not memorizing one tool.

Selenium WebDriver Beginner Checklist

Before moving to more advanced frameworks, use this Selenium WebDriver Tutorial checklist to make sure you can:

  • install Selenium
  • launch a browser
  • use Selenium Manager
  • open a URL
  • choose a stable locator
  • interact with page elements
  • handle dynamic behavior
  • assert expected results
  • close browser sessions
  • run a pytest test
  • diagnose common failures

Frequently Asked Questions

What is Selenium WebDriver?

Selenium WebDriver is an API and browser-automation technology used to control web browsers from code.

Is Selenium WebDriver the same as Selenium?

No. Selenium is the broader project, while WebDriver is its core browser-control API.

Do I need to install ChromeDriver manually?

Usually not in a standard modern Selenium setup. Selenium Manager can resolve and manage the required browser driver when one has not already been provided.

Which programming language should a Selenium beginner use?

Choose a language relevant to your work or target roles. Python is beginner-friendly, while Java, C#, JavaScript and other Selenium-supported languages may fit different teams.

Which is better: XPath or CSS selector?

Neither is universally better. Prefer whichever gives you a clear and stable locator for the element.

What is an explicit wait?

An explicit wait pauses test progression until a particular condition becomes true or its timeout is reached.

Why avoid time.sleep()?

A fixed sleep waits for a predefined period instead of adapting to the real application state, making tests potentially slower or less reliable.

What is Page Object Model?

Page Object Model organizes page-specific locators and interactions into reusable classes or objects.

Is Selenium still worth learning?

Yes when it matches the jobs, projects, or technology environments you are targeting. The testing concepts learned through Selenium also transfer to other browser-automation tools.

Final Takeaway

Learning Selenium WebDriver is not about memorizing dozens of commands.

Start with the core workflow:
launch browser -> choose stable locators -> interact -> wait for the correct state -> assert expected behavior -> understand failures

Once those fundamentals become comfortable, pytest, Page Objects, Selenium Grid, CI/CD, and more advanced automation topics become much easier to learn.

mubeen

SQA Engineer & WordPress Developer

Was this article helpful?

Table of Contents

Scroll to Top