Select Multiple Options in a Multi-Select List
Pick several options in a select element with the multiple attribute, clear previous choices, read back what is selected, and handle custom listboxes.
Problem
A “Notify me about” field is a <select multiple>. You need exactly “Releases” and “Security” selected. Clicking options one by one replaces the selection in some browsers, and the form may already have defaults selected from a previous save.
Solution
Use the Select helper. Confirm the element really is multi-select, clear everything, select each target by visible text, then read back the selected options to assert the final state.
import org.openqa.selenium.support.ui.Select;
public static void selectExactly(WebElement el, List<String> labels) { Select select = new Select(el); if (!select.isMultiple()) throw new IllegalArgumentException("Not a multi-select");
select.deselectAll(); for (String label : labels) select.selectByVisibleText(label);
List<String> actual = select.getAllSelectedOptions().stream() .map(WebElement::getText).map(String::trim).toList(); if (!new HashSet<>(actual).equals(new HashSet<>(labels))) { throw new AssertionError("Expected " + labels + " but selected " + actual); }}
selectExactly(driver.findElement(By.id("topics")), List.of("Releases", "Security"));from selenium.webdriver.support.select import Select
def select_exactly(el, labels): select = Select(el) if not select.is_multiple: raise ValueError("Not a multi-select")
select.deselect_all() for label in labels: select.select_by_visible_text(label)
actual = {o.text.strip() for o in select.all_selected_options} assert actual == set(labels), f"Expected {labels} but selected {actual}"
select_exactly(driver.find_element(By.ID, "topics"), ["Releases", "Security"])const { Select } = require('selenium-webdriver/lib/select');
async function selectExactly(el, labels) {const select = new Select(el);if (!(await select.isMultiple())) throw new Error('Not a multi-select');
await select.deselectAll();for (const label of labels) await select.selectByVisibleText(label);
const selected = await select.getAllSelectedOptions();const actual = await Promise.all(selected.map(async (o) => (await o.getText()).trim()));assert.deepStrictEqual(new Set(actual), new Set(labels));}
await selectExactly(await driver.findElement(By.id('topics')), ['Releases', 'Security']);using OpenQA.Selenium.Support.UI;
public static void SelectExactly(IWebElement el, IReadOnlyCollection<string> labels){ var select = new SelectElement(el); if (!select.IsMultiple) throw new ArgumentException("Not a multi-select");
select.DeselectAll(); foreach (var label in labels) select.SelectByText(label);
var actual = select.AllSelectedOptions.Select(o => o.Text.Trim()).ToHashSet(); if (!actual.SetEquals(labels)) throw new Exception($"Expected [{string.Join(", ", labels)}] but selected [{string.Join(", ", actual)}]");}
SelectExactly(driver.FindElement(By.Id("topics")), ["Releases", "Security"]);Why It Works
The Select helper clicks the matching option only if it is not already selected, and under the W3C WebDriver spec a click on an option inside a multiple select toggles that one option without clearing the others. Earlier choices are kept when you select the next one, with no modifier keys involved. deselectAll() gives you a known starting point regardless of saved defaults, and reading getAllSelectedOptions() back proves the form holds what you think it holds.
Custom Listboxes
Component libraries often render a multi-select as role="listbox" with aria-multiselectable="true" and role="option" children. There is no Select helper for these. Click each option while holding the platform modifier key, then assert on aria-selected:
Keys modifier = System.getProperty("os.name").startsWith("Mac") ? Keys.COMMAND : Keys.CONTROL;Actions actions = new Actions(driver).keyDown(modifier);for (String label : List.of("Releases", "Security")) { actions.click(driver.findElement(By.xpath("//*[@role='option'][normalize-space()='" + label + "']")));}actions.keyUp(modifier).perform();Many tag-style pickers (chips with a text box) instead want you to type and press Enter for each value. Check how a user does it and replicate that.
Gotchas
deselectAllon a single select throws (UnsupportedOperationException/NotImplementedError/InvalidOperationException). CheckisMultiplefirst, as above.- Visible text must match exactly, after whitespace normalisation. If labels include counts like “Security (3)”, select by
valueinstead. - Disabled options cannot be selected; recent Selenium versions throw rather than silently skipping. Assert they are disabled if that is the behaviour under test.
- Hidden native selects. Libraries like Select2 hide the real
<select>and draw their own UI.Selectmay still work on the hidden element, but it bypasses the widget; prefer driving the visible UI so the test matches the user.