In this blog, we discuss about handling the drop down elements in Selenium WebDriver.
Scenario to be automated:
- Launch the web browser
- Open your application (eg. "http://www.findnerd.com")
- Click on 'Nerd Digest' (Go to the web page where Dropdown list is available)
- Select the “Other Sites” from dropdown list of Searchbar
- Select the “Users” from dropdown list of Searchbar
- Select the “Nerd Digest” from dropdown list in Searchbar
Here is the Html Code for dropdown list:
<select id="searchOption" class="searchchoice" name="searchOption">
<option selected="selected" value="t">Nerd Digest </option>
<option value="u">Users </option>
<option value="o">Other Sites </option>
</select>
WebDriver Code goes as below:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class dropdown {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.findnerd.com");
WebElement nd = driver.findElement(By.xpath(".//*[@id='offshoreindialive']/div[2]/header/nav/ul/li[1]/a"));
nd.click();
WebElement dropdown = driver.findElement(By.id("searchOption"));
Select dd = new Select(dropdown);
dd.selectByIndex(2); // this will select 'Other Sites'
dd.selectByValue("u"); // this will select 'Users'
dd.selectByVisibleText("Nerd Digest"); // this will select 'Nerd Digest'
}
}
1) selectByIndex() method for selecting the value from dropdown list:
dd.selectByIndex(2);
In this command, we have selected the third value from the drop down list using the selectByIndex() method and parameterized it with the index value of the element.
2) selectByValue() method for selecting the value from dropdown list:
dd.selectByValue("u");
In this command, we have selected the value “Users” in the drop down using the selectByValue() method and parameterized it with the text available in the value attribute.
3) selectByVisibleText() method for selecting the value from dropdown list:
dd.selectByVisibleText("Nerd Digest");
In this command, we have selected the value “Nerd Digest” in the drop down using the selectByVisibleText() method and parameterized it with the text available on the user interface.
0 Comment(s)