How to select a value from a dropdown using Selenium webdriver
Overview
Selenium is a powerful tool for programmatically manipulating an internet browser. All major browsers can use it, and it runs on all major operating systems. It has scripts written in many different languages, including Python, Java, C#, and so on.
Install selenium python using pip.
pip install selenium
The Select class
The Select class in selenium is used to handle dropdowns.
The methods available in the Select class to select an option from the drop-down are mentioned below.
The select_by_visible_text() method
The select_by_visible_text() method selects all options that display text matching the argument.
The syntax to use the method is as follows:
drop.select_by_visible_text(text)
Note: The
textis the visible text to match against.
The select_by_value() method
The select_by_value() method selects all options that have a value matching the argument.
The syntax to use the method is as follows:
drop.select_by_value(value)
Note: Where
valueis the value to match against.
select_by_index() method
The select_by_index() method selects the option at the given index.
The syntax to use the method is as follows:
drop.select_by_index(index)
The option at the given index will be selected.
Code
import timefrom selenium import webdriverfrom selenium.webdriver.support.ui import Selectdriver = webdriver.Firefox(executable_path="path to driver")url = ""driver.get(url)drop_down_node = driver.find_element_by_id('#dropdown')drop = Select(drop_down_node)drop.select_by_index(2)time.sleep(4)driver.close()
Explanation
- Line 4: We create an instance of the firefox driver.
- Line 5: We define the URL to which is to be retrieved.
- Line 6: We use the driver to open the URL in the selenium browser.
- Line 7: We use the
find_element_by_idmethod to retrieve the element with the IDdropdown. - Line 8: We create an instance of the
Selectclass with the retrieved drop down from Line 7. - Line 9: We select the 2nd index of the dropdown.
- Line 10: The program is in sleep for 4 seconds so that we can observe the option from the selected dropdown.