Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 35 ยท Practice and Review

Practice Exercises with Solutions

Five hands-on Selenium exercises on locators, waits, page objects, forms and exceptions, each with a hint, a runnable stand-in solution and a discussion.

Reading about Selenium only takes you so far. Skill comes from writing locators, wait helpers and page objects yourself and seeing where they break. This lesson gives you five exercises that follow the course, from picking a locator to diagnosing an exception. Every exercise has a task, a hint and a solution you can run.

Selenium needs a browser and driver, so it cannot run on this site. The solutions are therefore stand-ins written in JavaScript: they use plain objects instead of a real browser, but the logic (ranking locators, polling, returning page objects, validating forms, classifying errors) is exactly what you would write around the real WebDriver calls. Real Selenium snippets are read-only.

Five exercises, five skills

Locators Pick the most stable one.
Waits Write a polling helper.
Page objects Return the next page.
Forms Validate and report errors.

Attempt each one before opening the solution.

1 / 2

Try each exercise on your own first, in the editor of the solution block if you like: replace my code with yours, run it and compare the output.

Exercise 1: choose the best locator

Task. You are given six elements described as plain data. Write bestLocator(element) that returns the most stable locator by this ranking: a test id first; then an id that does not contain digits (digits often mean generated ids); then name; then link text for <a> elements; then the first CSS class; and finally an XPath on the visible text as a last resort.

Hint. Think about which attributes survive a redesign. A class like btn-83a1f or an id like field-4821 is usually produced by a build tool and changes between releases. Read Choosing Stable Locators if you need a refresher.

In real Selenium you would then use the chosen strategy like this:

Python
driver.find_element(By.CSS_SELECTOR, "[data-testid='save']")
driver.find_element(By.ID, "email")
driver.find_element(By.NAME, "phone")

Solution.

JS Exercise 1 solution: a locator ranker

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Discussion. The save button has an unstable id and class, but the test id wins. The phone field has an id with digits, so the ranking falls through to its name. The toast has only classes, so it gets a weak CSS locator: a hint that the page needs a test id. The last element, with no attributes at all, is the case for XPath on text.

Exercise 2: write your own wait helper

Task. Write an async waitUntil(condition, options) that calls condition() repeatedly until it returns something truthy, then returns that value. It must stop after timeout milliseconds with a TimeoutError, pause interval milliseconds between tries, and swallow only the error types listed in options.ignore. Any other error must escape immediately.

Hint. This is what WebDriverWait(driver, 10).until(...) does. Keep the last ignored error so the timeout message can say why the condition never held. Read Implicit, Explicit and Fluent Waits for the real API.

The real thing, for comparison:

Python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException

wait = WebDriverWait(driver, timeout=10, poll_frequency=0.5,
                     ignored_exceptions=[NoSuchElementException])
button = wait.until(lambda d: d.find_element(By.ID, "save"))

Solution.

JS Exercise 2 solution: waitUntil

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Discussion. Case 5 is the important one. A TypeError means your test has a bug, and hiding it behind a polite timeout would waste hours. Selenium's WebDriverWait ignores NoSuchElementException by default for the same reason: that exception is an expected "not yet", while everything else is a real problem.

Exercise 3: page objects that return the next page

Task. Model a login screen and a dashboard. LoginPage.login(user, pass) must return a DashboardPage when the login worked and the same LoginPage when it did not. Add loginExpectingError for negative tests, and errorMessage().

Hint. The test then reads like a story (LoginPage(...).login(...).greeting()), and the types guide you: only the dashboard has greeting(). See The Page Object Model.

Solution.

JS Exercise 3 solution: return the next page

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Discussion. Returning different types from one method is convenient but can surprise you: the last two lines show that calling login with a bad password gives a LoginPage with no greeting. That is why loginExpectingError exists as a separate, honestly named method. Many teams prefer one method per outcome over methods that return different things depending on the data.

Exercise 4: validate a form and report errors

Task. Write validate(form) returning an object of errors keyed by field id: the name is required, the email must look like an address, the password needs 8 or more characters, and the confirmation must match. Then write render(errors) that prints an error summary line plus one line per field with aria-invalid=true.

Hint. In a real test you would read these messages from the page: driver.find_element(By.ID, "email").get_attribute("aria-invalid") returns "true" for an invalid field, and the summary is usually an element with role="alert". The project Form Validation Checks builds on this.

Solution.

JS Exercise 4 solution: validate and report

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Discussion. The first form is valid, so the summary says nothing is wrong; the second breaks all four rules at once. A good test checks both directions: the invalid case shows exactly the expected messages, and the valid case shows none.

Exercise 5: turn an exception into a next step

Task. Build a small lookup that takes a log line starting with a Selenium exception name and returns the likely cause and a first fix. Unknown names should say so rather than guess.

Hint. Knowing exceptions by heart pays off during debugging. Compare with Flaky Tests and Debugging and the exceptions table in the Selenium Cheat Sheet.

Solution.

JS Exercise 5 solution: exception triage

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Discussion. Each exception points at a different class of problem: timing (TimeoutException), page change (StaleElementReferenceException), overlap (ElementClickInterceptedException) or wrong state. An honest "Unknown" answer is better than a wrong tip.

Going further

Once these feel easy, try variations: extend bestLocator to return a By object; make waitUntil accept a custom message; give DashboardPage a logout() that returns a LoginPage; or add a rule to validate for phone numbers. Then build one of the projects, such as Login Test Suite.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the locator ranking prefer a test id over an id like field-4821?

    A test id is added for tests and has no styling or build-tool meaning, so it rarely changes.
  2. 2. In waitUntil, why must a TypeError escape immediately instead of being retried?

    Only expected 'not yet' errors are ignored. Everything else should fail loudly.
  3. 3. What does the return-the-next-page pattern give you?

    Each action returns the page object for where the user lands, so the next call is the next step of the journey.
  4. 4. An exercise log shows StaleElementReferenceException. What is the best first fix?

    The old reference points to a node that was replaced. A fresh lookup (ideally inside a wait) gets the new one.

Summary

  • Rank locators by stability: test id, plain id, name, link text, CSS class, text-based XPath last.
  • A wait helper polls a condition, ignores only expected "not yet" errors and reports why it timed out.
  • Page object methods return the page the user lands on; negative paths get their own method.
  • Form tests check both invalid and valid input, including aria-invalid and an error summary.
  • Exceptions are clues: learn what each one usually means.

Next, rehearse how to explain all of this in Selenium Interview Questions.