Skip to content
CodeKruPro

Automation tool (Selenium) · Java

Dropdowns and tables

Selecting options and reading web tables.

Learn: Dropdowns and web tables in Selenium Java7 minute read

Dropdowns and tables appear in almost every web app, so they appear in almost every automation interview. A dropdown lets the user pick one value from a list; a web table shows data in rows and columns. Questions range from "select India" to "find this customer's row across five pages of results and read the status".

Native dropdowns with Select

A native dropdown is a real <select> element in the HTML. Wrap it in Selenium's Select helper (a class made for dropdowns):

Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("India");
country.selectByValue("IN");
country.selectByIndex(2);                          // counts from 0
String chosen = country.getFirstSelectedOption().getText();
List<WebElement> options = country.getOptions();

There are three ways to choose. Visible text is what the user sees, which makes tests easy to read. Value is the hidden value attribute, which stays the same when labels are translated. Index counts from 0 and includes placeholder options such as "Choose one", so it breaks when the list changes; use it rarely. A missing text or value throws NoSuchElementException.

Multi-select lists

A multi-select list has the multiple attribute and lets users pick several options. isMultiple() tells you which kind you have. On a multi-select, getAllSelectedOptions() lists the choices and deselectByVisibleText, deselectByValue, deselectByIndex and deselectAll() remove them. On a single-choice select, deselectAll() throws UnsupportedOperationException.

Custom and auto-suggest dropdowns

Many sites draw dropdowns with div and li elements. Select only accepts a <select> and throws UnexpectedTagNameException on anything else. So act like a user:

driver.findElement(By.id("country-picker")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("ul.options")));
driver.findElement(By.xpath("//ul[@class='options']/li[normalize-space()='India']")).click();

An auto-suggest box shows matching values as you type. Type a few letters, wait for the suggestions, and click the one whose text matches exactly. Then check the value the control shows.

Checking the options

"Check there are no duplicate options" and "check they are sorted" are common follow-ups. Read the labels once, then use plain Java:

List<String> labels = new ArrayList<>();
for (WebElement o : country.getOptions()) labels.add(o.getText().trim());

Set<String> seen = new HashSet<>();
List<String> duplicates = new ArrayList<>();
for (String label : labels) {
    if (!seen.add(label)) duplicates.add(label);
}
Assert.assertTrue(duplicates.isEmpty(), "Duplicates: " + duplicates);

List<String> sorted = new ArrayList<>(labels);
Collections.sort(sorted);
Assert.assertEquals(labels, sorted, "options are not in order");

A Set holds each value only once. Set.add returns false when the value is already there, which is how the loop spots repeats. Leave a placeholder out of the sort check if it should stay first.

Web tables

A table is made of rows (tr), each holding cells (td, or th for headers):

List<WebElement> headers = driver.findElements(By.cssSelector("#orders thead th"));
List<WebElement> rows = driver.findElements(By.cssSelector("#orders tbody tr"));
for (WebElement row : rows) {
    List<WebElement> cells = row.findElements(By.tagName("td"));
    System.out.println(cells.get(0).getText() + " - " + cells.get(1).getText());
}

Calling findElements on a row searches only inside that row.

Dynamic tables, step by step

A dynamic table changes: rows load late, get sorted, or spread across pages. Never rely on fixed row numbers:

  1. Wait for the table to finish loading: the spinner (a loading icon) gone, or at least one row.
  2. Read the header cells once and note the index of each column name, so you read "Status" by name.
  3. Find the row by its data: //tr[td[normalize-space()='Ravi']].
  4. Read the cell at the mapped column in that row.
  5. For paging, click Next while the row is missing and the button is enabled, wait for the old first row to go stale (stalenessOf: the page replaced that row, so the old reference no longer works; see Selenium exceptions and debugging), and stop after a maximum number of pages.

How to answer in an interview

For dropdowns, first ask "is it a real select element?", then name the matching approach. For tables, walk through the five steps above. If the app has a search box or filter, say you would use it before paging, because users do.

Common mistakes

  • Wrapping a div-based dropdown in Select.
  • Clicking the first suggestion: typing "Ind" may list Indonesia first.
  • Selecting by index when options can change.
  • Reading cells by fixed row numbers in a sorted or paged table.
  • Keeping row elements in a list and then sorting the table, which makes them stale (the old references no longer work).

Recap

Use Select for real select elements and user-like clicks with waits for everything else. Check option lists with a set. Read tables by header name and row data, not by position, and page with a loop that always ends.

17 questions0/17 solved

StatusQuestionDifficultyAsked in
Not startedWhich option does select by index 1 choose?EasyAsked in: Accenture, Capgemini, Infosys +3
Not startedXPath for a cell in the row of a known nameMediumAsked in: Accenture, Infosys, TCS +1
Not startedChoose a dropdown option by visible textEasyAsked in: Accenture, Capgemini, Infosys +3
Not startedCount the rows and columns of a web tableEasy-MediumAsked in: Accenture, Infosys, TCS +1
Not startedChoose a dropdown option by valueEasyAsked in: Accenture, Capgemini, Infosys +3
Not startedChoose a dropdown option by indexEasyAsked in: Accenture, Capgemini, Infosys +3
Not startedList every option in a dropdownEasy-MediumAsked in: Accenture, Capgemini, Infosys +3
Not startedSelect and deselect in a multi-select listMediumAsked in: Accenture, Capgemini, Infosys +3
Not startedRead the option that is already selectedEasyAsked in: Accenture, Capgemini, Infosys +3
Not startedRead the header cells of a tableEasy-MediumAsked in: Accenture, Infosys, TCS +1
Not startedRead specific cells from a tableEasy-MediumAsked in: Accenture, Infosys, TCS +1
Not startedRead every row of a tableMediumAsked in: Accenture, Infosys, TCS +1
Pro+Using Select on a dropdown built from divs (Java)MediumAsked in: Accenture, Infosys, TCS
Pro+Handle a custom or auto-suggest dropdownMediumAsked in: Accenture, Infosys, TCS
Pro+Check that a dropdown has no duplicate options (Java)Easy-MediumAsked in: Capgemini
Pro+deselectAll() on a single-choice dropdown (Java)Medium
Pro+Read a dynamic web tableMediumAsked in: Accenture, Infosys, TCS +1
Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan