There are multiple methods available for handling static dropdowns in a page in Selenium. The static dropdowns are an integral part of a web page. This type of UI elements are mostly developed for birthday selection on a page.
A dropdown is not an element alone. It is a group of elements. For example for selection of age or birth date, we have multiple options to be selected for day, month and the year. Thus the approach is to first get the primary element and then move to its sub elements for selection.
Select class is provided by the Selenium API which works with the static dropdown on the page. We need to import selenium.webdriver.support.select.Select to work with the static dropdowns having the select tags in the html code.
The methods under the Select class are listed below −
select_by_visible_text(args) − Selection with the help of text displayed as option.
This method is the simplest one which selects the option based on the visible text. NoSuchElementException thrown if there is no option which matches with the text given in the argument.
d = Select(driver.find_element_by_id("selection")) d.select_by_visible_text('Tutorialspoint')
select_by_index(args) − Selection with the help of index of option.
This method selects the option based on the index of the specific option. The index of the elements mostly start with 0. NoSuchElementException thrown if there is no index which matches with the index given in the argument.
d = Select(driver.find_element_by_id("selection")) d.select_by_index(1)
select_by_value(args) − Selection with the help of value of option.
This method selects the option based on the value of the specific option. NoSuchElementException thrown if there is no value which matches with the value given in the argument.
d = Select(driver.find_element_by_id("selection")) d.select_by_value('Selenium')
Code Implementation for selection of options in dropdown.
from selenium import webdriver from selenium.webdriver.support.select import Select #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/tutor_connect/index.php") #to refresh the browser driver.refresh() #select class provide the methods to handle the options in dropdown d = Select(driver.find_element_by_xpath("//select[@name='seltype']")) #select an option with visible text method d.select_by_visible_text("By Name") #select an option with index method d.select_by_index(0) #select an option with value method d.select_by_value("name") #to close the browser driver.close()