Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 35 ยท Interacting with the Page

Forms, Checkboxes and Dropdowns

Automate forms with Selenium: the Select class for dropdowns, checkbox and radio state, reading validation messages, and submitting a form safely.

Forms are where most web applications collect their data, and they are where most end-to-end tests spend their time: sign-up, checkout, search filters, settings pages. A form mixes several kinds of control, and each one is driven in a slightly different way. Text fields take typing, checkboxes and radio buttons hold state, and dropdowns need their own helper.

This lesson covers the Select helper class, how to set and read the state of checkboxes and radios, how to find out why a form refused to submit, and how to submit a form the way a user does. It builds on Clicking and Typing.

You cannot run Selenium or a browser on this site. The Selenium code is read-only, and the runnable examples are JavaScript stand-ins: a model of the Select class and a small form with validation and a submit handler that prints its data, so the logic is visible.

A native <select> is not driven by clicking its options one by one. Selenium offers the Select wrapper:

HTML
<select id="country" name="country">
  <option value="">Choose...</option>
  <option value="ca">Canada</option>
  <option value="de">Germany</option>
  <option value="jp">Japan</option>
</select>
Python
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select

country = Select(driver.find_element(By.ID, "country"))

country.select_by_visible_text("Germany")   # what the user reads
country.select_by_value("jp")               # the value attribute
country.select_by_index(1)                  # position, starting at 0

print(country.first_selected_option.text)   # the chosen option
print([o.text for o in country.options])    # every option, in order

Prefer select_by_visible_text or select_by_value. An index depends on the order of the list, which changes when someone adds a country. Visible text matches the user's view; the value is stable when the labels are translated. The constructor raises an error if the element is not a <select>, which is a helpful signal that you located the wrong element.

For a <select multiple>, extra methods exist: all_selected_options, deselect_by_value, deselect_by_visible_text, deselect_by_index and deselect_all. They raise an error on a single-choice dropdown, because deselecting from one-of-many does not make sense. is_multiple tells you which kind you have.

Custom dropdowns are a different story. Many designs draw their own menu from div and ul elements and have no <select> at all. Select cannot drive those. Click the control to open it, wait for the options to appear, then click the one you want like any other element:

Python
driver.find_element(By.CSS_SELECTOR, '[data-testid="country-trigger"]').click()
driver.find_element(By.XPATH, "//li[@role='option'][normalize-space()='Germany']").click()

Which control, which tool

Text field clear(), then send_keys().
Checkbox Check is_selected(), then click.
Radio Click the one you want.
Select Wrap it with Select.

Custom menus built from divs are clicked like any other element.

1 / 2

Checkboxes and radio buttons

A checkbox is a toggle, so clicking it twice leaves it unchecked again. A test should ask for a state, not perform a blind click. Check the current state first:

Python
def set_checkbox(element, wanted: bool):
    if element.is_selected() != wanted:
        element.click()

set_checkbox(driver.find_element(By.ID, "newsletter"), True)
set_checkbox(driver.find_element(By.ID, "terms"), True)

This helper is idempotent: you can call it repeatedly and the box ends in the right state. It also gives your tests a pleasant, declarative style.

Radio buttons are exclusive within a group that shares a name. Clicking one unchecks the others. To pick a radio by its label text, find the input by value, or select the input inside its label:

Python
driver.find_element(By.CSS_SELECTOR, "input[name='plan'][value='pro']").click()
assert driver.find_element(By.CSS_SELECTOR, "input[name='plan']:checked").get_attribute("value") == "pro"

Be aware that some designs hide the real <input> and draw a custom box with CSS. In that case is_displayed() is False for the input, and a click raises an error. Click the visible label, or <label for="...">, which toggles the associated input just as a user's click does, and then verify the input's is_selected().

Reading validation messages

Forms refuse bad input in two ways, and tests must know which one they face.

Browser validation uses attributes such as required, type="email", pattern and minlength. The browser blocks the submit itself and shows a bubble. The page does not reload, no submit event fires, and the bubble is outside the page content, so you cannot find it with a locator. Read the message from the element's validationMessage property, or ask whether the control is valid:

Python
email = driver.find_element(By.ID, "email")
email.send_keys("not-an-email")
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()

print(email.get_attribute("validationMessage"))   # text written by the browser
print(driver.execute_script("return arguments[0].validity.valid", email))   # False

The wording of validationMessage differs between browsers and languages, so assert on validity.valid rather than the exact text unless you pin the browser.

Application validation is performed by your own JavaScript or the server, which writes messages into the page, for instance <p class="error" role="alert">Enter a valid email address.</p>. Those are normal elements you locate and read with .text. After a submit that comes back with errors, wait for the message to appear before asserting (see Implicit, Explicit and Fluent Waits).

Submitting

The most faithful submit is the one a user performs: click the submit button, or press Enter in a field.

Python
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
# or
driver.find_element(By.ID, "email").send_keys(Keys.ENTER)

element.submit() works too, but it submits the form without clicking the button, so anything attached to the button's click is skipped. Use it only when no usable button exists.

After the submit, assert on what changed: a new URL, a confirmation message, a row added to a table. Do not assume it worked because nothing broke.

A stand-in for the Select class

Here is a model of Select with the same method names, over a simple list of options. It shows why selecting by index is fragile and why a single-choice list refuses deselect_all.

JS A model of Select

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

No output.

A stand-in for a validated form

The next example models a sign-up form: collect the values, run the browser-style validation, and, if everything is valid, call a submit handler that prints the data. Nothing is sent anywhere. This is also how your own page's submit handlers should look in lesson demos, since a sandboxed preview must not post to real servers.

JS A form with validation and a submit handler

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

No output.

In a Selenium test the three attempts correspond to three tests: an empty form, invalid values, and the happy path. Notice that attempts one and two never reached the handler. That mirrors browser validation, which stops the submit, so a test for the error case checks the validation state and messages instead of waiting for a page change.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Select method is the least robust when the list of options may be reordered later?

    An index depends on the position of the option in the list. Text and value identify the option itself.
  2. 2. A checkbox is already ticked. What does driver.find_element(...).click() do to it?

    A click toggles a checkbox. Check is_selected() first, as in a set_checkbox helper, so the state ends up as wanted.
  3. 3. Why can't Select drive a dropdown built from div and ul elements?

    Select requires a <select> element and raises an error for anything else. Open a custom menu by clicking it, then click an option element.
  4. 4. A required field is empty and the user clicks Submit. The browser shows a bubble. How should a test check this?

    The bubble is drawn by the browser outside the page content, so locators cannot find it. The element's validity state and validationMessage property can be read.

Summary

  • Wrap a native <select> in Select and choose by visible text or value; avoid indexes. Custom menus are ordinary elements that you click.
  • A checkbox click toggles, so test is_selected() first and write a helper that sets the state you want.
  • Radios are exclusive per name; click the input or its visible label, then check the selected one.
  • Browser validation blocks the submit and is read with validity and validationMessage; application validation writes messages into the page.
  • Submit by clicking the button or pressing Enter, then assert on what changed.

Next, learn mouse and keyboard gestures beyond a plain click in Mouse and Keyboard: the Actions API.