EthicsComputerCourses
Join training +91 90532 10052

Selenium Web Testing

HTML · Lesson 204 of 234 Advanced 12 min read Updated

By the end of this lesson you will be able to explain how WebDriver controls a browser, write Selenium 4 tests in JavaScript (with a short Python version), choose locators that survive redesigns, replace sleeps with explicit waits, organise tests with page objects and decide when Selenium or Playwright fits a project better.

What you should know first: HTML Testing Fundamentals and Playwright Browser Testing, whose page under test (Aarav's cricket trial form) we test again here. The software testing course has a Python-first Selenium WebDriver lesson and a full Page Object Model lesson. Versions checked in November 2026: Selenium 4.52.0 (released 29 October 2026) for both the selenium-webdriver npm package and the Python selenium package. All outputs below are real, from Chrome 157 on Windows.

WebDriver: a standard way to drive browsers

WebDriver is a W3C standard (a Recommendation since June 2018) that defines how a program controls a browser. Your test does not touch the browser directly. It sends commands to a driver, a small program made by the browser vendor:

Text
Your test code  --HTTP + JSON-->  driver  --native control-->  browser
(selenium-webdriver)             (chromedriver, geckodriver,   (Chrome, Firefox,
                                  msedgedriver, safaridriver)   Edge, Safari)

Think of ordering at a restaurant in Kochi. You speak to the waiter in a common language (the WebDriver protocol). The waiter knows how this particular kitchen works (the driver). You never walk into the kitchen yourself. Because the protocol is a standard, the same test can drive any browser that ships a driver.

A newer two-way protocol, WebDriver BiDi, is being standardised at the W3C. It lets the browser push events, such as console messages, to your test. Selenium 4 already uses parts of it.

Selenium is the oldest and most widely used project built on WebDriver. It gives you client libraries for JavaScript, Python, Java, C# and Ruby.

Step 1: install and run a first script

Selenium is a library, not a test runner, so you pair it with one. Node.js 22 has a built-in runner, node:test, so the only package needed is Selenium itself:

Terminal
npm install selenium-webdriver

Save Aarav's page from the Playwright lesson as site/index.html and serve it on http://localhost:3000 with any static server. Then create first.mjs:

JavaScript
import { Builder, By } from "selenium-webdriver";
import chrome from "selenium-webdriver/chrome.js";

const options = new chrome.Options().addArguments("--headless=new");
const driver = await new Builder().forBrowser("chrome").setChromeOptions(options).build();
try {
  await driver.get("http://localhost:3000/");
  console.log("Title:", await driver.getTitle());
  const h1 = await driver.findElement(By.css("h1"));
  console.log("H1:", await h1.getText());
} finally {
  await driver.quit();
}
Terminal
node first.mjs
Output
Title: Book a trial | Pune Cricket Academy
H1: Book a free trial session

--headless=new runs Chrome without a window. Remove it to watch the browser. The finally block always calls quit(), otherwise failed runs leave Chrome processes behind.

Selenium Manager: no more driver downloads

We never downloaded chromedriver. Since Selenium 4.6, Selenium Manager, a tool bundled with every Selenium package, checks your installed browser version and fetches the matching driver. On this run it detected Chrome 157 and cached chromedriver 157.0.8103.78 in the user's .cache/selenium folder. Next time it reuses the cached copy.

Before Selenium Manager, every Chrome update broke test suites with a "this version of ChromeDriver only supports Chrome version N" error until someone downloaded a new driver. You will still see old tutorials that set a driver path by hand. You can delete that code.

Locators: prefer id, name and CSS

A locator tells Selenium how to find an element. The main ones are By.id(), By.name(), By.css(), By.linkText() and By.xpath().

ChoiceExampleWhy
BestBy.id("mobile")Ids are unique and rarely change
GoodBy.name("mobile")The name is tied to the form data the server expects
GoodBy.css("#trial button[type=submit]")Short, readable, fast; anchored to a stable id
Use with careBy.xpath("//button[normalize-space()='Book trial']")Finds by visible text, which CSS cannot do, but breaks when wording changes
AvoidBy.xpath("/html/body/form/input[2]")Depends on the exact position of every parent

XPath is a query language for walking a document tree. It is powerful, but absolute paths and position numbers such as [2] describe where an element is, not what it is. The demo below runs five locators that all aim at the mobile field. Click "Redesign the page": a banner with a search box is added and the form is wrapped in a new <div>, as designers do all the time.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <title>Which locators survive a redesign?</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    .banner { background: #fff3cd; padding: 8px; }
    table { border-collapse: collapse; margin-top: 12px; }
    th, td { border: 1px solid #aaa; padding: 4px 8px; text-align: left; }
    .bad { background: #ffebee; }
  </style>
</head>
<body>
  <form id="trial">
    <label for="player">Player name</label>
    <input id="player" name="player">
    <label for="mobile">Mobile number</label>
    <input id="mobile" name="mobile" type="tel">
    <button type="submit">Book trial</button>
  </form>
  <p>
    <button type="button" id="redesign">Redesign the page</button>
  </p>
  <table>
    <thead><tr><th scope="col">Locator (CSS or XPath)</th><th scope="col">Finds</th></tr></thead>
    <tbody id="rows"></tbody>
  </table>

  <script>
    // Each locator is meant to find the mobile number field
    const locators = [
      ["css", "#mobile"],
      ["css", "input[name='mobile']"],
      ["css", "#trial input[type='tel']"],
      ["xpath", "/html/body/form/input[2]"],
      ["xpath", "(//input)[2]"]
    ];

    function find(kind, query) {
      if (kind === "css") return document.querySelector(query);
      return document.evaluate(query, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }

    function check() {
      const rows = document.querySelector("#rows");
      rows.replaceChildren();
      for (const [kind, query] of locators) {
        const el = find(kind, query);
        const result = !el ? "NOTHING" : el.id === "mobile" ? "mobile field (correct)" : `#${el.id} (WRONG element)`;
        const tr = rows.insertRow();
        tr.insertCell().textContent = `${kind}: ${query}`;
        tr.insertCell().textContent = result;
        if (!result.includes("correct")) tr.className = "bad";
      }
    }

    document.querySelector("#redesign").addEventListener("click", () => {
      // A designer adds a banner with a search box and wraps the form in a card
      const banner = document.createElement("div");
      banner.className = "banner";
      banner.innerHTML = '<label for="q">Search</label> <input id="q" name="q">';
      const card = document.createElement("div");
      const form = document.querySelector("#trial");
      form.before(banner, card);
      card.append(form);
      check();
    });

    check();
  </script>
</body>
</html>

At first all five rows say "mobile field (correct)". After the redesign, the three CSS locators still work. The absolute XPath finds nothing, which at least fails loudly. The position-based (//input)[2] is worse: it quietly finds the player name field, so a test could type a phone number into the wrong box and report a confusing failure later. Good HTML habits from earlier levels, such as unique ids and proper name attributes, make tests stable.

Waits: explicit, never sleep

The coaches list appears only after an API answers. If the test looks too early, it finds nothing. We ran this version, with no wait:

JavaScript
await driver.findElement(By.id("load")).click();
const items = await driver.findElements(By.css("#coaches li"));
assert.equal(items.length, 3);
Output
✖ loads three coaches (no wait) (1219.5754ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

  0 !== 3

There are three ways to wait, and only one is right for this:

  • Sleep (driver.sleep(2000)): always waits the full time. Too short on a slow day, wasted time on a fast one.
  • Implicit wait (driver.manage().setTimeouts({ implicit: 2000 })): makes every findElement retry until an element exists. It cannot wait for text or visibility.
  • Explicit wait (driver.wait(condition, timeout)): polls a specific condition, such as "at least one li exists" or "this text is not empty", and continues the moment it is true.

The Selenium docs warn against mixing implicit and explicit waits, because the timeouts combine unpredictably. Use explicit waits. The simulation below runs 20 fake loads with delays between 200 and 1,800 ms and tests each one both ways.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <title>Fixed sleep vs explicit wait</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    output { display: block; margin-top: 8px; font-family: monospace; white-space: pre; }
  </style>
</head>
<body>
  <h1>Fixed sleep vs explicit wait</h1>
  <p>Each run starts a fake "Load coaches" request that takes 200 to 1,800 ms, like a real network on a busy day.</p>
  <button type="button" id="go">Run 20 tests each way</button>
  <output id="sleep"></output>
  <output id="wait"></output>

  <script>
    // Fixed, repeatable delays (a seeded pseudo-random sequence)
    let seed = 7;
    const delays = Array.from({ length: 20 }, () => {
      seed = (seed * 16807) % 2147483647;
      return 200 + (seed % 1601);
    });

    const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

    // The "page": the list fills in after the request finishes
    function startLoad(delay) {
      const list = { items: 0 };
      setTimeout(() => { list.items = 3; }, delay);
      return list;
    }

    // Like driver.sleep(1000) followed by a check
    async function testWithSleep(delay) {
      const list = startLoad(delay);
      await pause(1000);
      return list.items === 3;
    }

    // Like driver.wait(until..., 5000): check every 100 ms, give up after 5 s
    async function waitUntil(condition, timeout = 5000) {
      const start = performance.now();
      while (performance.now() - start < timeout) {
        if (condition()) return performance.now() - start;
        await pause(100);
      }
      return null;
    }
    async function testWithWait(delay) {
      const list = startLoad(delay);
      return waitUntil(() => list.items === 3);
    }

    document.querySelector("#go").addEventListener("click", async () => {
      const slept = await Promise.all(delays.map(testWithSleep));
      const waited = await Promise.all(delays.map(testWithWait));
      const passedSleep = slept.filter(Boolean).length;
      const times = waited.filter((t) => t !== null);
      const average = Math.round(times.reduce((a, b) => a + b, 0) / times.length);
      document.querySelector("#sleep").textContent =
        `Fixed sleep 1000 ms: ${passedSleep}/20 passed, every test waited 1000 ms`;
      document.querySelector("#wait").textContent =
        `Explicit wait:       ${times.length}/20 passed, average wait about ${average} ms`;
    });
  </script>
</body>
</html>

The sleep strategy passes 15 of 20 and always spends a full second. The explicit wait passes all 20 and spends only as long as each load needed, about 800 ms on average. Raising the sleep to 2 seconds would pass, but every test would then waste time on fast days.

Step 2: page objects and a real suite

A page object is a class that knows one page's locators and actions. Tests call trial.book(...) instead of repeating findElement calls. When the HTML changes, you fix one file. This is trial-page.mjs:

JavaScript
import { By, Select, until } from "selenium-webdriver";

export class TrialPage {
  constructor(driver) {
    this.driver = driver;
  }
  async open() {
    await this.driver.get("http://localhost:3000/");
  }
  async book({ name, mobile, batch }) {
    await this.driver.findElement(By.id("player")).sendKeys(name);
    await this.driver.findElement(By.id("mobile")).sendKeys(mobile);
    const select = new Select(await this.driver.findElement(By.id("batch")));
    await select.selectByVisibleText(batch);
    await this.driver.findElement(By.name("rules")).click();
    await this.driver.findElement(By.css("#trial button[type=submit]")).click();
  }
  async statusText() {
    const status = await this.driver.findElement(By.id("status"));
    await this.driver.wait(until.elementTextMatches(status, /\S/), 3000);
    return status.getText();
  }
  async loadCoaches() {
    await this.driver.findElement(By.id("load")).click();
    const items = await this.driver.wait(until.elementsLocated(By.css("#coaches li")), 5000);
    return Promise.all(items.map((li) => li.getText()));
  }
}

until.elementTextMatches waits for the status to contain any non-space text. until.elementsLocated waits for at least one list item. And trial.test.mjs:

JavaScript
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { Builder } from "selenium-webdriver";
import chrome from "selenium-webdriver/chrome.js";
import { TrialPage } from "./trial-page.mjs";

let driver;
let page;

before(async () => {
  const options = new chrome.Options().addArguments("--headless=new");
  driver = await new Builder().forBrowser("chrome").setChromeOptions(options).build();
  page = new TrialPage(driver);
});

after(() => driver.quit());

test("books a trial with valid data", async () => {
  await page.open();
  await page.book({ name: "Aarav Shah", mobile: "9876543210", batch: "Evening" });
  assert.equal(
    await page.statusText(),
    "Thanks, Aarav Shah! Your trial is booked for the Evening batch."
  );
});

test("loads three coaches", async () => {
  await page.open();
  const names = await page.loadCoaches();
  assert.equal(names.length, 3);
});
Terminal
node --test --test-reporter=spec "tests/*.test.mjs"
Output
✔ books a trial with valid data (3143.3862ms)
✔ loads three coaches (472.4574ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4646.1089

The first test is slower because it includes starting Chrome. Note that the coaches test calls a real public API, so it fails whenever that API is down. In a real suite, point the page at a local stub server during tests, as HTML Testing Fundamentals advised.

The same test in Python

The Python bindings use the same ideas with snake_case names. After python -m pip install selenium:

Python
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

options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)
try:
    driver.get("http://localhost:3000/")
    driver.find_element(By.ID, "load").click()
    items = WebDriverWait(driver, 5).until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#coaches li"))
    )
    print(driver.title)
    print(len(items), "coaches loaded")
finally:
    driver.quit()
Output
Book a trial | Pune Cricket Academy
3 coaches loaded

Selenium Grid in brief

Selenium Grid runs tests on remote machines, many at once, across browsers and operating systems. The simplest setup is one machine in standalone mode. Download the server .jar from the Selenium site; it needs Java installed:

Terminal
java -jar selenium-server-4.52.0.jar standalone

Then point the builder at it with new Builder().usingServer("http://localhost:4444").forBrowser("firefox"). For bigger setups a hub receives requests and sends them to several nodes, and the project publishes Docker images for each browser. Cloud device labs offer the same protocol, so tests written for Grid usually run there with only a URL change.

Selenium or Playwright?

Selenium 4Playwright
ProtocolW3C WebDriver (plus parts of BiDi)Its own protocol to patched browser builds
LanguagesJavaScript, Python, Java, C#, RubyJavaScript/TypeScript, Python, Java, .NET
BrowsersReal installed Chrome, Edge, Firefox, SafariBundled Chromium, Firefox and WebKit builds; can also use installed Chrome and Edge
WaitingExplicit waits you writeAuto-waiting and retrying assertions built in
Test runnerBring your own (node:test, Mocha, pytest, JUnit)Playwright Test included
Network mockingPossible through BiDi, more setuppage.route() built in
Remote and parallel runsSelenium Grid; supported by most cloud labsParallel workers and --shard built in; can connect to remote browsers
Best fitLarge existing suites, Java or C# teams, real Safari on macOSNew front-end projects that want speed and fewer flaky tests

Neither is "better" everywhere. Many companies still maintain large Selenium suites, often in Java, so knowing both helps in interviews.

Common mistakes

  • driver.sleep() everywhere. Slow and still flaky; wait for a condition.
  • Mixing implicit and explicit waits. Timeouts add up unpredictably; pick explicit waits.
  • Absolute or index-based XPath. Breaks or, worse, finds the wrong element after small changes.
  • Locators copied into every test. Put them in page objects.
  • Forgetting quit(). Leftover browser processes slow down and eventually crash CI machines.

Interview questions

1. What is WebDriver, and how does Selenium use it?

WebDriver is a W3C standard protocol for controlling browsers. Selenium's client library sends WebDriver commands as HTTP requests to a browser-specific driver, such as chromedriver, which controls the browser. Because it is a standard, the same test code works across browsers.

2. What does Selenium Manager do?

Since Selenium 4.6 it is bundled with Selenium. It detects the installed browser version, downloads the matching driver and caches it, so you no longer manage driver files or paths by hand.

3. What is the difference between implicit and explicit waits?

An implicit wait is a global setting that makes every element search retry until the element exists. An explicit wait polls one specific condition, such as visibility or text, with its own timeout. Explicit waits are preferred, and the two should not be mixed.

4. Which locators do you prefer and why?

Id first, then name, then short CSS selectors anchored on stable attributes. I use XPath only when I need something CSS cannot do, like matching text, and never absolute or position-based paths, because they break when the layout changes.

5. What is the Page Object Model?

A design pattern where each page or component has a class holding its locators and user actions. Tests call those methods and assert on the results. When the HTML changes, only the page object changes, not every test.

Key points

  • WebDriver is a W3C standard; Selenium sends its commands to a browser-specific driver.
  • Selenium Manager (since 4.6) finds and caches the right driver automatically.
  • Prefer By.id, By.name and short CSS; avoid absolute and index-based XPath.
  • Use explicit waits (driver.wait with until conditions), not sleeps or mixed implicit waits.
  • Page objects keep locators and actions in one place; pair Selenium with a runner such as node:test or pytest.
  • Grid runs suites remotely; Playwright offers more built in, Selenium offers wider language and real-browser reach.

Exercise

Extend the Selenium suite for Aarav's page:

  1. Add a submitEmpty() method to TrialPage that clicks Book trial without filling anything.
  2. Write a test that, after submitEmpty(), checks that the active element is the player name field (use driver.switchTo().activeElement()) and that the status is still empty.
  3. Add a By.xpath locator that finds the Book trial button by its text, and explain in a comment why it is acceptable here but riskier than By.css.
Show solution
JavaScript
// In TrialPage
async submitEmpty() {
  // XPath by text: readable, but breaks if the button wording changes,
  // for example to "Book a trial". The CSS locator is tied to the form id instead.
  await this.driver.findElement(By.xpath("//button[normalize-space()='Book trial']")).click();
}

// In trial.test.mjs
test("empty submit keeps focus on the first field", async () => {
  await page.open();
  await page.submitEmpty();
  const active = await driver.switchTo().activeElement();
  assert.equal(await active.getAttribute("id"), "player");
  const status = await driver.findElement(By.id("status"));
  assert.equal(await status.getText(), "");
});

Import By in the test file too. The browser's own required check blocks the submit and focuses the first invalid field, so no wait is needed: the focus moves during the click itself.

Quick Quiz

1. What does a WebDriver driver such as chromedriver do?

2. Which locator is most likely to find the wrong element after a banner with an input is added above a form?

3. Why is an explicit wait better than driver.sleep(2000)?

4. Since which Selenium version is Selenium Manager bundled?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call