Handling Drop-Downs - Selenium WebDriver
Handling dropdown is a common scenario in web application testing. Selenium WebDriver provides a way to select an option from a dropdown menu using the Select
class. In this tutorial, we will learn how to handle dropdowns in Selenium WebDriver.
Syntax
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_name('dropdown_name'))
# select by visible text
select.select_by_visible_text('Option1')
# select by value
select.select_by_value('value1')
# select by index
select.select_by_index(0)
Example
Suppose we want to select an option from the following HTML code which contains a dropdown menu.
<select name="colors">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
Here is how we can use the above code to select an option from the dropdown menu using Selenium WebDriver-
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get("https://example.com")
# Locate the dropdown element
dropdown = Select(driver.find_element_by_name('colors'))
# Select an option using visible text
dropdown.select_by_visible_text('Blue')
Output
The above code will select the option "Blue" from the dropdown list and the output will depend on the requirements.
Explanation
In the above example, we first locate the dropdown element using find_element_by_name()
method and then create a Select
object by passing the dropdown element as an argument. Using the select_by_visible_text()
method, we can select an option based on the visible text of the option.
We can also select an option based on its index or value using select_by_index()
and select_by_value()
methods respectively.
Use
Dropdown menus are commonly used in web applications. Testing these menus is important to verify that the expected options exist and that the selected option is properly recorded.
Important Points
- Make sure to first locate the dropdown element using the appropriate locator.
- The
Select
class provides methods to select an option based on visible text, value, or index. - To deselect all selected options, use the
deselect_all()
method of theSelect
class.
Summary
Handling dropdown menus is a common scenario in web application testing. Selenium WebDriver provides the Select
class to handle dropdown menus. We can use the select_by_visible_text()
, select_by_value()
, and select_by_index()
methods of the Select
class to select an option from a dropdown menu based on visible text, value, or index respectively.