Working with select list elements
Select lists have special behaviors compared to other elements.
Select elements can require quite a bit of boilerplate code to automate. To reduce this, and make your tests cleaner, there is a Select class in the Selenium support package. To use it, you will need the following import statement:
import org.openqa.selenium.support.ui.Select;
You are then able to create a Select object using a WebElement that references a <select> element.
                                
WebElement selectElement = driver.findElement(By.id("selectElementID"));
Select selectObject = new Select(selectElement);
                                
                              
                        
                                
<select>
 <option value=value1>Bread</option>
 <option value=value2 selected>Milk</option>
 <option value=value3>Cheese</option>
</select>
                                
                              
                        
                                
// Return a List<WebElement> of options that have been selected
List<WebElement> allSelectedOptions = selectObject.getAllSelectedOptions();
// Return a WebElement referencing the first selection option found by walking down the DOM
WebElement firstSelectedOption = selectObject.getFirstSelectedOption();
// Return a ListWebElement of options that the select element contains
List<WebElement> allAvailableOptions = selectObject.getOptions();
// Deselect an option based upon the select element's internal index
selectObject.deselectByIndex(1);
// Deselect an option based upon its value attribute
selectObject.deselectByValue("value1");
// Deselect an option based upon its text
selectObject.deselectByVisibleText("Bread");
// Deselect all selected option elements
selectObject.deselectAll();
//Finally, some select elements allow you to select more than one option. You can find out if your select element is one of these by using:
Boolean doesThisAllowMultipleSelections = selectObject.isMultiple();