How to handle dropdown in selenium WebDriver?
Two ways to handle dropdown –
<select id="id_state" class="form-control" name="id_state" style=""> <option value="">-</option> <option value="1">Alabama</option> <option value="2">Alaska</option> <option value="3">Arizona</option> <option value="4">Arkansas</option> <option value="5">California</option> <option value="6">Colorado</option> <option value="7">Connecticut</option> <option value="8">Delaware</option>
WebElement element = driver.findElement(By.id("mySelectID")); Select s= new Select(element); s.selectByIndex(0);
WebElement element = driver.findElement(By.id("mySelectID")); Select s= new Select(element); s.selectByValue("Value");
WebElement element = driver.findElement(By.id("mySelectID")); Select s= new Select(element); s.selectByVisibleText("Option");
2. Without Using Select class
Method 1:
In this example, we find the option via a complex xpath, then click on it:
WebElement myoption = driver.findElement(By.xpath( "//Select[@id='mySelectID']/option[normalize-space(text())='Option']") ); myOption.click();
Method 2:
In this example, we find all the options, iterate over them, and click the one we want. This is useful if you have some more complex criteria.
WebElement mySelectElm = driver.findElement(By.id("mySelectID")) Select mySelect= new Select(mySelect); List<WebElement> options = mySelect.getOptions(); for (WebElement option : options) { if (option.getText().equalsIgnoreCase("Option") { option.click(); } }
This is all about Selecting dropdown. However, note that, method 1 is more recommended, that is by using Select class.
Refer below video on same –
Hope This Helps !!!!!