Selenium Testing and WebDriver Tutorial: Setup and Your First Test

selenium testing tutorial

Selenium testing uses Selenium WebDriver to control a real browser from code, so you can check that a web app works the way users expect. This tutorial covers how Selenium works, how to set it up, the core WebDriver commands, and how to write and run your first test in Python and Java.

Key takeaways
The 30-second version of this article
Selenium testing uses Selenium WebDriver to control a real browser from code in Java, Python, C#, Ruby, or JavaScript.
Since Selenium 4.6, Selenium Manager finds and downloads browser drivers for you, so setup takes a library, a browser, and a few lines of code.
A good first test sets up a browser, acts, waits with explicit waits, asserts, and closes the browser at the end.
Selenium is free to use, but locators, waits, reports, Grid, and CI take ongoing work as a suite grows.
Katalon Studio is built on Selenium, so you can keep your WebDriver skills and add recording, self-healing, reports, and CI runs with KRE.

Selenium testing is the practice of using Selenium, a free and open-source project, to automate a real web browser from code. You write a script that opens a page, finds elements, types, clicks, and checks the result, and Selenium WebDriver carries out each step in Chrome, Firefox, Edge, or Safari the way a user would.

This Selenium WebDriver tutorial covers how Selenium works, whether it's really free, how to set it up with Selenium 4 and Selenium Manager, the core WebDriver commands, and how to write and run your first Selenium test in Python and Java. Each code sample in this guide was run against a public practice site before publishing.

What is Selenium testing?

Selenium logo

Selenium is a set of tools for browser automation. Teams use it for Selenium automation testing of web apps: functional tests, regression suites, and cross-browser checks that would take hours to repeat by hand.

Selenium started in 2004, when Jason Huggins, an engineer at ThoughtWorks, built a JavaScript tool to avoid testing the same web app manually again and again. That tool grew into the Selenium project, and Selenium WebDriver later became the basis of the W3C WebDriver standard that major browsers support.

You can write Selenium tests in Java, Python, C#, Ruby, and JavaScript, which are the official language bindings. Selenium handles the browser; you add a test runner (such as pytest, JUnit, or TestNG) to organize tests, run them, and report pass or fail.

How Selenium works: WebDriver, Grid, and IDE

Selenium has three main parts. Most Selenium test automation uses WebDriver, and teams add Grid or IDE when they need them.

Selenium WebDriver

WebDriver is the core of Selenium testing. It's a programming interface that sends commands to a browser through a driver made for that browser:

  • ChromeDriver for Google Chrome
  • GeckoDriver for Mozilla Firefox
  • msedgedriver for Microsoft Edge
  • safaridriver for Safari

A test run usually follows these steps:

  1. Your script creates a WebDriver object for a browser, for example webdriver.Chrome() in Python.
  2. WebDriver starts a session and opens a controlled browser window.
  3. The script sends commands, such as open a URL, click a button, or type into a field, and the browser carries them out like a user would.
  4. The browser returns results: success or failure, plus any data you asked for, such as an element's text.
  5. When the test finishes, the script ends the session and the browser closes.

To act on a page, WebDriver first has to find elements. Selenium supports these locator strategies: ID, name, class name, tag name, link text, CSS selector, and XPath. Our guide to locators in Selenium explains when to use each one.

Selenium Grid

Selenium Grid runs WebDriver tests on remote machines, so you can run tests in parallel and on different browsers and operating systems. Tests send their commands to the Grid, and the Grid routes them to a machine with a matching browser.

Selenium mechanism

Grid can run in three ways:

  • Standalone: all Grid components run in one process on one machine. It's the simplest way to start.
  • Hub and node: a hub receives test requests and sends each one to a node, a machine that runs the browser. Selenium's docs call it the most used role.
  • Distributed: each Grid component runs separately, usually on different machines, for large setups.

You don't need Grid to get started. A single machine with a browser is enough for your first Selenium tests.

Selenium IDE

Selenium IDE is a record and playback extension for Chrome and Firefox. You click Record, use your web app, and IDE saves each action as a command with a target and a value. You can then replay the test and see each step pass or fail.

Selenium testing tutorial

IDE also saves several locators for each element, so if one fails during playback it tries the others. You can set breakpoints to pause a run and inspect the page at that step.

Selenium testing guide

IDE is a quick way to sketch a test. Most teams write their long-term suites with WebDriver code, which is what the rest of this tutorial covers.

Is Selenium testing free?

Yes. Selenium is open source under the Apache 2.0 license, so there's no license fee for WebDriver, Grid, or IDE, for personal or commercial use.

The framework is free; the work around it isn't. With Selenium on its own, your team builds and maintains:

  • A test project, a test runner, and a folder structure
  • Locators and waits that keep working as the UI changes
  • Test data and environment setup
  • Reports, screenshots, and logs for failed tests
  • Grid machines or a cloud service for parallel and cross-browser runs
  • CI pipelines that run the tests on each change

For a small suite, that's manageable. As the suite grows, keeping tests stable usually takes more time than writing new ones. Plan for that time when you estimate the cost of Selenium testing.

How to set up Selenium WebDriver

Selenium 4 makes setup much shorter than it used to be. Since Selenium 4.6, Selenium Manager ships with the Selenium language bindings. When your code starts a browser, Selenium Manager finds the right driver for your installed browser and downloads it if it's missing. From Selenium 4.11, it can also download Chrome itself, and later Firefox and Edge, if they aren't installed.

That means you no longer download ChromeDriver by hand, unzip it, or add a driver path to your code. You need three things: a language runtime, the Selenium library, and a browser.

Install Selenium for Python

  1. Install Python 3 from python.org.
  2. Create a virtual environment for your project, then install Selenium and pytest with pip: pip install selenium pytest
  3. Check the setup with a short script.
from selenium import webdriver

driver = webdriver.Chrome()  # Selenium Manager finds or downloads the driver
driver.get("https://the-internet.herokuapp.com/login")
print(driver.title)
driver.quit()

If a Chrome window opens and the script prints "The Internet", your setup works.

Install Selenium for Java

  1. Install a JDK (version 11 or later) and a build tool such as Maven or Gradle.
  2. Add the selenium-java dependency (group org.seleniumhq.selenium) and a test runner such as JUnit 5 to your pom.xml or build.gradle. Check the Selenium downloads page for the latest version; this tutorial uses 4.52.0.
  3. Check the setup with the same steps in Java.
WebDriver driver = new ChromeDriver(); // Selenium Manager finds or downloads the driver
driver.get("https://the-internet.herokuapp.com/login");
System.out.println(driver.getTitle());
driver.quit();

Set up WebDriver for Chrome, Firefox, Edge, and Safari

With Selenium Manager, each browser needs one line to start:

Browser

Python

Java

Notes

Chrome

webdriver.Chrome()

new ChromeDriver()

Selenium Manager handles the driver

Firefox

webdriver.Firefox()

new FirefoxDriver()

Selenium Manager handles GeckoDriver

Edge

webdriver.Edge()

new EdgeDriver()

Selenium Manager handles msedgedriver

Safari

webdriver.Safari()

new SafariDriver()

macOS only; safaridriver ships with macOS

Safari needs one extra step. Turn on remote automation once, either by running safaridriver --enable in Terminal or by enabling the Develop menu in Safari's settings and selecting Allow Remote Automation.

To run tests without opening a browser window, for example on a CI server, add a headless option:

options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)

Core Selenium WebDriver commands

These are the commands you'll use most in Selenium testing. Python and Java use the same commands with different naming styles.

Task

Python

Java

Open a page

driver.get(url)

driver.get(url)

Get the page title

driver.title

driver.getTitle()

Get the current URL

driver.current_url

driver.getCurrentUrl()

Go back, forward, or refresh

driver.back(), driver.forward(), driver.refresh()

driver.navigate().back(), forward(), refresh()

Maximize the window

driver.maximize_window()

driver.manage().window().maximize()

Find one element

driver.find_element(By.ID, "username")

driver.findElement(By.id("username"))

Find many elements

driver.find_elements(By.CSS_SELECTOR, "a")

driver.findElements(By.cssSelector("a"))

Type into a field

element.send_keys("text")

element.sendKeys("text")

Clear a field

element.clear()

element.clear()

Click

element.click()

element.click()

Read text

element.text

element.getText()

Check state

element.is_displayed(), is_enabled(), is_selected()

element.isDisplayed(), isEnabled(), isSelected()

Wait for a condition

WebDriverWait(driver, 10).until(...)

new WebDriverWait(driver, Duration.ofSeconds(10)).until(...)

Close the browser

driver.quit()

driver.quit()

WebDriver also has commands to move into an iframe and back, accept or dismiss JavaScript alerts, and move between browser windows and tabs.

Write your first Selenium test

Now put the commands together in a real test. The example uses the login page on the-internet.herokuapp.com, a public practice site built for test automation.

Here's the test case:

Component

Details

Test case ID

TC001

Description

Verify login with valid and invalid credentials

Preconditions

The login page at /login is reachable

Test steps

1. Open the login page. 2. Enter the username and password. 3. Click Login.

Test data

Username: tomsmith; password: SuperSecretPassword! (valid) or a wrong password

Expected result

Valid: a success message and the /secure page. Invalid: an error message and the user stays on /login

Pass or fail

Pass if the message and URL match; fail otherwise

The test follows the usual structure of a Selenium test:

  1. Set up: start a browser before each test.
  2. Act: open the page, find the fields, type, and click.
  3. Wait: wait for the result message to appear instead of pausing for a fixed time.
  4. Assert: check the message text and the URL.
  5. Clean up: close the browser after each test, even if it fails.

For more on writing test cases and reporting results, see how to build a good test report.

Your first Selenium test in Python

Save this as test_login.py:

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

BASE_URL = "https://the-internet.herokuapp.com"


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


def log_in(driver, username, password):
    driver.get(f"{BASE_URL}/login")
    driver.find_element(By.ID, "username").send_keys(username)
    driver.find_element(By.ID, "password").send_keys(password)
    driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
    return WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.ID, "flash"))
    )


def test_valid_login(driver):
    flash = log_in(driver, "tomsmith", "SuperSecretPassword!")
    assert "You logged into a secure area!" in flash.text
    assert driver.current_url.endswith("/secure")


def test_invalid_password(driver):
    flash = log_in(driver, "tomsmith", "wrong-password")
    assert "Your password is invalid!" in flash.text
    assert driver.current_url.endswith("/login")

Run it from the project folder with pytest -v. pytest finds both tests, opens Chrome for each, and reports two passed tests. The fixture's code after yield runs even when an assertion fails, so the browser closes either way.

Your first Selenium test in Java

The same test in Java with JUnit 5. Save it as LoginTest.java under src/test/java:

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.Duration;
import org.junit.jupiter.api.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

class LoginTest {
    private static final String BASE_URL = "https://the-internet.herokuapp.com";
    private WebDriver driver;

    @BeforeEach
    void setUp() { driver = new ChromeDriver(); }

    @AfterEach
    void tearDown() { driver.quit(); }

    private WebElement logIn(String username, String password) {
        driver.get(BASE_URL + "/login");
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).sendKeys(password);
        driver.findElement(By.cssSelector("button[type='submit']")).click();
        return new WebDriverWait(driver, Duration.ofSeconds(10))
                .until(ExpectedConditions.visibilityOfElementLocated(By.id("flash")));
    }

    @Test
    void validLogin() {
        WebElement flash = logIn("tomsmith", "SuperSecretPassword!");
        assertTrue(flash.getText().contains("You logged into a secure area!"));
        assertTrue(driver.getCurrentUrl().endsWith("/secure"));
    }

    @Test
    void invalidPassword() {
        WebElement flash = logIn("tomsmith", "wrong-password");
        assertTrue(flash.getText().contains("Your password is invalid!"));
        assertTrue(driver.getCurrentUrl().endsWith("/login"));
    }
}

Run it with mvn test. @BeforeEach and @AfterEach do the same job as the pytest fixture: a fresh browser for each test, closed afterward.

To run the same test against more data, such as a list of users, see data-driven testing with Selenium.

Common Selenium testing problems and how to fix them

Timing and waits

A common cause of failing Selenium tests is timing: the script looks for an element before the page has rendered it. Avoid fixed pauses such as time.sleep(5), which slow every run and still fail on a slow day. Use explicit waits instead, as the test above does: WebDriverWait waits only as long as needed for a condition such as "element is visible" or "URL contains /secure". Don't mix implicit and explicit waits in the same test, since that can make wait times hard to predict.

Fragile locators

A test that finds elements by long XPath paths or generated class names breaks when the page layout changes. Prefer stable IDs, names, or dedicated test attributes, and keep locators in one place, such as a page object, so a UI change means one fix instead of many. See locators in Selenium for examples of each strategy.

Flaky tests

A flaky test passes and fails on the same code. Common causes are shared test data, tests that depend on each other's order, animations, and network delays. Give each test its own data and its own browser session, as the fixture above does, and investigate a flaky test before you retry it. Our guide to flaky tests covers more causes and fixes, and debugging in Selenium shows how to find why a test failed.

Keep your Selenium skills and extend them in Katalon Studio

Writing a first test is the quick part. As a suite grows, much of the work goes into locators, waits, reports, and CI setup. Katalon Studio is built on Selenium and Appium, so you can keep what you know about WebDriver and upgrade the parts around it:

  • Keep your code. Existing Selenium scripts can be brought into a Studio project rather than rewritten. In custom keywords, written in Groovy or Java, DriverFactory.getWebDriver() returns the active WebDriver, so the commands in this tutorial still work.
  • Record when it's faster. Web Recorder Plus captures your actions and the page elements as you use the app, and you can edit the recorded steps before you save the test case. With a Katalon Studio Enterprise (KSE) license, the AI Recording Agent (beta) can record steps from a scenario you describe in plain English; it's unavailable with a Free license, even with your own API key.
  • Spend less time on broken locators. Classic self-healing tries an object's other saved locators (XPath, attributes, CSS, image, and Smart Locator) when the default one fails, then suggests the working locator for your approval. AI self-healing steps in when classic self-healing can't find the element and uses a large language model to suggest a new locator. Both need an active Katalon Studio license; AI self-healing also needs an AI model configured in Studio or your own API key. Read more about self-healing test automation.
  • Fewer timing failures. Smart Wait waits for elements to be ready before each web step, so you write fewer explicit waits.
  • Reports without extra setup. Studio produces HTML, CSV, and PDF test suite reports, with steps, logs, and screenshots for each test case.
  • Run in CI. Run the same tests from the command line with Katalon Runtime Engine (KRE) in pipelines such as GitHub Actions. CI execution needs an active KRE license.

Studio Free covers web, mobile, API, and desktop authoring for individual testers, with no time limit.

Frequently asked questions

Huyen Nguyen
Huyen NguyenTechnical Writer, Katalon

Huyen Nguyen is an experienced technical writer in the software testing industry. With strong technical expertise and a deep understanding of Katalon products, she creates clear, practical guides that support testers at every skill level.

Connect on LinkedIn →
True Platform has arrived

Test everything. Ship with confidence.

From generating test cases to spotting failures, Katalon's AI works across your entire pipeline, automatically.

The Next Evolution of Manual Testing: Introducing Katalon AI Test Runner

Introducing Katalon AI Test Runner. Watch it run manual test cases live, with evidence for every pass and fail.

Live webinar
9:00 to 10:00 AM EST · Live online
Alex MartinsVP of Strategy
Gia EspositoSenior Solutions Engineer
Save your seat