Before starting lets first create a demo page to work with.
HTML Code for demo page
  1. <html>
  2. <head>
  3. <title>Multi select Drop Down List Box</title>
  4. </head>
  5. <body>
  6. <div align="center">
  7. <p>Which device do you own?</p>
  8. <p>Please select it using the below dropdown</p>
  9. <select name="devices">
  10. <option selected> Please select</option>
  11. <option value="iphone">iPhone</option>
  12. <option value="lenovo">Lenovo</option>
  13. <option value="samsung">Samsung</option>
  14. <option value="xiaomi">Xiaomi</option>
  15. <option value="windows">Windows Phone</option>
  16. </select>
  17. </div>
  18. </body>
  19. </html>
'Select' class provides us some useful methods to interact with dropdowns to select dropdown option using below methods.
  • selectByIndex
  • selectByValue
  • selectByVisibleText
selectByIndex: This method will select the dropdown option based on the dropdown index.
  1. public class HandleDropDown {
  2. public void selectByIndexExample(WebDriver driver){
  3. WebElement element=driver.findElement(By.name("devices"));
  4. Select se=new Select(element);
  5. se.selectByIndex(1); //this will select iPhone
  6. }
  7. public static void main(String[] args) throws InterruptedException {
  8. WebDriver driver=new FirefoxDriver();
  9. driver.get("D:\\dp.html");
  10. HandleDropDown dp=new HandleDropDown();
  11. dp.selectByIndexExample(driver);
  12. }
  13. }
selectByValue: This method will select the dropdown option based on the value matching with the given argument.
  1. public class HandleDropDown {
  2. public void selectByValueExample(WebDriver driver){
  3. WebElement element=driver.findElement(By.name("devices"));
  4. Select se=new Select(element);
  5. se.selectByValue("lenovo"); //This will select Lenovo
  6. }
  7. public static void main(String[] args) throws InterruptedException {
  8. WebDriver driver=new FirefoxDriver();
  9. driver.get("D:\\dp.html");
  10. HandleDropDown dp=new HandleDropDown();
  11. dp.selectByValueExample(driver);
  12. }
  13. }
selectByVisibleText: This method will select the dropdown option based on displaying text in the dropdown.
  1. public class HandleDropDown {
  2. public void selectByVisibletextExample(WebDriver driver){
  3. WebElement element=driver.findElement(By.name("devices"));
  4. Select se=new Select(element);
  5. se.selectByVisibleText("Windows Phone"); //This will select Windows Phone
  6. }
  7. public static void main(String[] args) throws InterruptedException {
  8. WebDriver driver=new FirefoxDriver();
  9. driver.get("D:\\dp.html");
  10. HandleDropDown dp=new HandleDropDown();
  11. dp.selectByVisibletextExample(driver);
  12. }
  13. }