It can be used always to select the option from dropdown.
It can be used only when the dropdown menu has been created using select tag.
By using Select class , you can select the drop down options in many ways.
like selectByVisibleText ,selectByIndex, selectByValue
Steps to use Select Class:
1. Initiate a web driver session with any browser.2. Strore a single or a list of web elements like
WebElement element=driver.findElement(By.name("Bread");
3. Initialize the Select class and pass the webelement as an parameter.
4. Then select the options from drop down by using below methods:
selectByVisibleText()
selectByIndex()
selectByValue()
Ex:
WebElement element=driver.findElement(By.name("Fruits");
Select selectele =new Select(element);
selectele .selectByIndex(1);
selectele .selectByVisibleText("Apple");
DeSelect:
In the same way we can deselect the options from dropdown.For deselect we are using below methods :
deselectByVisibleText()
deselectByIndex()
deselectByValue()
deselectAll()
Ex:
WebElement element=driver.findElement(By.name("Fruits");
Select selectele =new Select(element);
selectele .deselectByIndex(1);
selectele .deselectByVisibleText("Apple");
Some more Functions of Select Class:
getOptions( ) : List<WebElement> It takes no parameter and returns List<WebElements>.getAllSelectedOptions( ) : List<WebElement> It takes no parameter and returns List<WebElements>.
getFirstSelectedOptions(): WebElement return type.
isMultiple(): Boolean Return type.
Ex: Select selectele = new Select(driver.findElement(By.id("someid")));
List <WebElement> ListCount = selectele .getOptions();
System.out.println(ListCount .size());