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
Select classThe 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.
select_by_visible_text() methodThe 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.
select_by_value() methodThe 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() methodThe 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.
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()
find_element_by_id method to retrieve the element with the ID dropdown.Select class with the retrieved drop down from Line 7.