Do not Drop out when you face drop down
You may have come across a millions of website and, most of them will have a drop down feature. Drop downs are must needed thing when the user has to select a choice from mutliple lists. So let's see how to work on drop down with Selenium.
NOTE: Pay attention to the import statements that we use in our programs. In previous example we have used import org.openqa.selenium.Alert. This will take care of the alert related functionalities. Similarly for drop downs, we are going to use org.openqa.selenium.support.ui.Select. Let's code for the drop down.
Lets go to http://www.echoecho.com/htmlforms11.htm and work with the drop down they have got.
package seleniumBasics;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HandlingDropDowns {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\Elcot\\Desktop\\drivers\\gecko\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.echoecho.com/htmlforms11.htm");
//find the drop down first
WebElement dropDown= driver.findElement(By.name("dropdownmenu"));
//pass the web element to Select as below
Select selectValue= new Select(dropDown);
selectValue.selectByIndex(0); //select by index position
//sleep included to slow down the process
Thread.sleep(2000);
selectValue.selectByValue("Cheese"); //select by value
Thread.sleep(2000);
selectValue.selectByVisibleText("Milk"); // select byvisible text
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
IMPORTANT NOTE: I am using thread.sleep in order to see whats happening on the web page, else the execution would be faster and we cant realise. So for beginner purpose, I am using. It is advisable not to encourage the usage of sleep in your actual code as it decreases the performance. There are some concepts in Selenium for Waiting. We will explore that later.