In order to select a dropdown value using Selenium WebDriver we have to create a Select an element and will not use the default WebElements provided by Selenium Webdriver.
Let's consider below drop-down example to select a value using Selenium WebDriver.
<option value="option1">Ahmedabad</option>
<option value="option2">Hyderabad</option>
<option value="option3">Mumbai</option>
<option value="option4">Pune</option>
</select>
WebElement CitySelection = driver.findElement(By.id("citySelect"));
Select dropdown= new Select(CitySelection);
Another method is directly you can pass in WebElement as below
Select dropdown = new Select(driver.findElement(By.id("citySelect")));
1.selectByVisibleText(String)
2.selectByIndex(int)
3.selectByValue(String)
dropdown.selectByVisibleText("Hyderabad")
dropdown.selectByIndex(2)
index =1 means Ahmedabad
index=2 means Hyderabad
drodown.selectByValue("option2")
dropdown.selectByValue("option1")
Let's consider below drop-down example to select a value using Selenium WebDriver.
1.HTML Dropdown Code:
<select id="citySelect"><option value="option1">Ahmedabad</option>
<option value="option2">Hyderabad</option>
<option value="option3">Mumbai</option>
<option value="option4">Pune</option>
</select>
1.1 Identify the HTML Element to Select value
Selenium WebDriver providing WebElement class to identify the or store web element as belowWebElement CitySelection = driver.findElement(By.id("citySelect"));
Select dropdown= new Select(CitySelection);
Another method is directly you can pass in WebElement as below
Select dropdown = new Select(driver.findElement(By.id("citySelect")));
1.2 Select an Option
You can select drodown options by three ways1.selectByVisibleText(String)
2.selectByIndex(int)
3.selectByValue(String)
2.1 selectByVisibleText:
You can select dropdown value by matching visible text as belowdropdown.selectByVisibleText("Hyderabad")
2.2 selectByIndex:
You can select the dropDown value by index attribute of an element as belowdropdown.selectByIndex(2)
index =1 means Ahmedabad
index=2 means Hyderabad
2.3 selectByValue:
You can select dropDown value by Optioon Value in above HTML code we've used multiple options 1,2,3,4 and code will bedrodown.selectByValue("option2")
dropdown.selectByValue("option1")
3.Complete Selenium Webdriver Code as follows:
WebElement CitySelection = driver.findElement(By.id("citySelect")); Select dropdown= new Select(CitySelection); dropdown.selectByIndex(2); dropdown.selectByValue("option1"); dropdown.selectByVisibleText("Hyderabad");
No comments:
Post a Comment