Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Selenium

Practical, exam-oriented notes on Selenium WebDriver: what it is, its architecture, key concepts (locators, waits, drivers, POM), common commands and syntax, worked examples, common mistakes and exam tips for software-testing students.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Selenium is used to automate web-browser actions so testers and engineers can run repeatable functional tests against web applications. Engineers use Selenium to create regression suites, run cross-browser checks, and integrate UI tests into CI/CD pipelines (for faster, repeatable verification of features).

Key ideas

Start from the goal: we want software tests that exercise a web application's user interface without a human doing clicks and typing.

  • Selenium — a suite of tools for automating web browsers. It is not one single program but a set of components (WebDriver, Grid, IDE). Define it precisely: Selenium is a framework that provides client libraries to send commands that control browsers through browser-specific driver programs. Assumption: browser and driver versions are compatible.

  • Browser Driver — a small executable (for example, chromedriver, geckodriver) that receives commands from client libraries and drives the browser. It translates WebDriver protocol requests to browser-internal actions.

  • WebDriver — the language-specific API (for example Java, Python bindings) that the test code uses. WebDriver sends HTTP requests per the W3C WebDriver protocol to a browser driver, which performs actions in the browser.

  • WebDriver Protocol / W3C WebDriver — the wire protocol that specifies how commands are encoded and sent between client and driver. Historically there was a JSON Wire Protocol; the current standard is the W3C WebDriver spec (check your Selenium version for details).

  • Locator — a way to find elements in the page DOM. Common locators: id, name, className, tagName, linkText, partialLinkText, cssSelector, xpath. Definition: A locator is a selector string or strategy used by WebDriver to return a WebElement.

  • WebElement — an object representing an element in the web page. It provides actions: click(), sendKeys(), getText(), getAttribute(), etc.

  • Implicit Wait — a global wait instructing WebDriver to poll the DOM for a given time when trying to find elements. Definition: set once on the WebDriver instance and applies to all find operations.

  • Explicit Wait (WebDriverWait) — wait until a specific condition is true for a particular element or state (for example, until element is clickable). Definition: a wait with polling and timeout applied for a specific condition.

  • FluentWait — like explicit wait but allows specifying polling interval and ignoring specific exceptions. Assume default polling 500 ms unless changed.

  • Page Object Model (POM) — a design pattern: represent each page (or fragment) as a class containing locators and operations. Definition: POM separates test logic from UI structure to increase maintainability.

  • Selenium Grid — a system to run tests in parallel on multiple machines/browsers. Components: Hub (receives tests) and Nodes (execute tests). In Selenium Grid 4, the architecture is Router/Distributor/Session Map/Nodes (or a single Standalone process), but many exam diagrams still use the legacy Hub/Node terminology; state which version you are drawing. Draw this: one box labeled "Hub" (or "Router/Distributor" for Grid 4), arrows from multiple test client boxes to it, and arrows from it to several Node boxes; each Node box connected to a browser instance.

  • Test Framework integration — Selenium is used with frameworks like JUnit / TestNG (Java) to provide setup/teardown, assertions, test grouping and parallel execution.

Architecture diagram to draw for exams (describe exactly): Draw five boxes left-to-right. Leftmost: "Test Client (Java/Python)". Right of it: "Selenium Client Library (WebDriver)". Then: "Browser Driver (chromedriver/geckodriver)". Then: "Browser (Chrome/Firefox)". Optionally above these, draw "Selenium Grid Hub" connected to multiple "Node (Driver + Browser)" boxes. Label arrows: client -> library -> driver -> browser. Annotate that the protocol used is the W3C WebDriver protocol (HTTP with JSON payloads over localhost or remote).

Assumptions to state in exam answers: a) correct driver for browser version is installed and on PATH (or path provided), or automatically resolved by Selenium Manager (Selenium 4.6+), b) tests run with sufficient permissions, c) network/firewall allows driver-client communication for remote setups.

Formulas

WebDriver driver = new ChromeDriver(); — create a new browser instance; driver is a WebDriver reference (Java). Applies when ChromeDriver binary is available or resolved by Selenium Manager (Selenium 4.6+). To run headless in CI: ChromeOptions options = new ChromeOptions(); options.addArguments("--headless=new"); WebDriver driver = new ChromeDriver(options); driver.get("http://example.com"); — navigate browser to a URL; URL is a String. WebElement el = driver.findElement(By.id("username")); — locate element by id and store as WebElement. el.sendKeys("myUser"); — type text into an input element; applies to editable elements. el.click(); — click the element; applies to clickable elements. driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(n)); — set implicit wait to n seconds (Selenium 4 syntax uses Duration). Applies globally for findElement calls. WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(n)); — create explicit wait; use wait.until(ExpectedConditions.elementToBeClickable(By.id("id"))); to wait for condition. driver.switchTo().frame("frameName"); — switch driver's context to an iframe by name/id/index/WebElement. String handle = driver.getWindowHandle(); — get current window handle; use driver.getWindowHandles() for all handles. driver.close(); — close current window; driver.quit(); — quit entire session and browser processes. Select s = new Select(driver.findElement(By.id("selectId"))); s.selectByVisibleText("Option"); — select from dropdowns. Actions a = new Actions(driver); a.moveToElement(el).click().perform(); — advanced user interactions like hover, drag-and-drop. Alert alert = driver.switchTo().alert(); alert.accept(); — switch to Javascript alert and accept it. RemoteWebDriver rd = new RemoteWebDriver(new URL("http://grid-host:4444"), new ChromeOptions()); — run test on Selenium Grid 4+ (recommended base URL; /wd/hub is for legacy Grids). Symbols: URL is Grid address; options/capabilities specify browser/config.

(If your Selenium version differs in method signatures, verify usage; see verify list.)

Worked examples

Example 1 — Automate a login form (Java, step-by-step trace). Given: a login page at http://demo/login with fields id="user" and id="pass" and button id="loginBtn". After successful login, a span id="welcome" contains "Welcome, Alice". Steps:

  1. Setup: WebDriver driver = new ChromeDriver(); // assume chromedriver on PATH.
  2. Navigate: driver.get("http://demo/login");
  3. Wait: driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5)); // implicit wait for element searches.
  4. Locate username: WebElement u = driver.findElement(By.id("user")); — found or wait until timeout.
  5. Action: u.sendKeys("alice");
  6. Locate password and enter: driver.findElement(By.id("pass")).sendKeys("p@ss");
  7. Click login: driver.findElement(By.id("loginBtn")).click();
  8. Explicit wait for welcome text: new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.textToBePresentInElementLocated(By.id("welcome"), "Welcome"));
  9. Assert: String txt = driver.findElement(By.id("welcome")).getText(); assertEquals("Welcome, Alice", txt);
  10. Cleanup: driver.quit(); Trace comments: if element not found, implicit wait polls DOM up to 5 s; after click, explicit wait polls every 500 ms default until text appears or 10 s passes. Final step asserts exact text; on failure record screenshot (use ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)).

Example 2 — Handling multiple windows (small trace). Scenario: clicking a link opens a new browser window. Steps:

  1. Save parent handle: String parent = driver.getWindowHandle();
  2. Click link that opens new window.
  3. Get all handles: Set<String> all = driver.getWindowHandles();
  4. For each handle h in all: if (!h.equals(parent)) { driver.switchTo().window(h); break; }
  5. Perform actions in child window, e.g., verify URL or close: driver.close();
  6. Switch back: driver.switchTo().window(parent); Note: forgetting to switch back is a common cause of later failures.

Example 3 — Model answer (theory): Explain Page Object Model and show why it improves tests. Answer (structured): 1) Definition: POM uses a class per page with locators and methods representing page actions. 2) Benefits: reduces duplication, isolates locator changes in single place, improves readability. 3) Show a small class sketch: class LoginPage { private WebDriver d; By user=By.id("user"); By pass=By.id("pass"); By btn=By.id("loginBtn"); LoginPage(WebDriver d){this.d=d;} void login(String u,String p){d.findElement(user).sendKeys(u); d.findElement(pass).sendKeys(p); d.findElement(btn).click();} } 4) Explain test code uses LoginPage.login("a","b"); so locators changes only inside LoginPage.

Common mistakes

  • Confusing WebDriver (API) with Browser Driver (chromedriver).
  • Using brittle locators (absolute XPath) instead of stable ids/css selectors.
  • Overusing Thread.sleep() instead of waits — leads to flaky tests.
  • Setting Implicit wait and explicit waits poorly together (can cause unexpected timeouts).
  • Forgetting to quit driver in teardown causing zombie browser processes.
  • Not switching context when dealing with frames/alerts/windows.
  • Not handling synchronization (race conditions when page updates dynamically), and not re-finding elements after DOM updates leading to StaleElementReferenceException (re-locate elements or use waits).
  • Forgetting to match browser version and driver binary version.

For your exam

Kinds of questions:

  • Definitions and short notes (define Selenium, WebDriver, locators, waits, Grid, POM).
  • Comparisons (Selenium RC vs WebDriver, implicit vs explicit wait).
  • Small programs/snippets (write a Selenium script to login or click and verify).
  • Diagrams (draw architecture of Selenium client-driver-browser and Grid).
  • Design questions (explain POM benefits, how to integrate with TestNG).
  • Troubleshooting (explain why a test fails to find element; propose fixes).

What full-marks answers include:

  • Clear definitions (bold / precise) and assumptions (driver versions, network).
  • Short, correct code snippets or syntax lines (state language, e.g., Java).
  • For diagrams: labels and arrow directions, note of protocol used.
  • For design/essay: list advantages, trade-offs, example class code for POM.
  • For waits/troubleshooting: explain expected condition, recommend explicit waits, show code and reason.

Quick check

  1. What Selenium component talks directly to the browser process?
  2. Give two locator strategies and one advantage of each.
  3. After a click that opens a new window, what WebDriver methods do you use to interact with the new window and then return to the original?

Answers: 1) Browser Driver (e.g., chromedriver). 2) id — fast and stable if available; cssSelector — flexible and expressive; often more concise than complex XPath (performance is similar in modern drivers). 3) getWindowHandles() to find handles, switchTo().window(handle) to switch, then switchTo().window(parentHandle) to return.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?