How to select an option in a static dropdown in Selenium?

SeleniumAutomation TestingTesting Tools

We can select an option in a static dropdown in Selenium webdriver. Selenium can handle static dropdowns with the help of the Select class. A dropdown is identified with select tagname and its options are represented with the tagname option. The statement - from selenium.webdriver.support.select import Select should be added to work with Select class.

Methods under the Select class are listed below −

  • select_by_visible_text (arg) – it shall select all the options which displayed text matches with the argument.

Syntax−

sel = Select (driver.find_element_by_id ("name"))
sel.select_by_visible_text ('Visible Text')
  • select_by_value (arg) – it shall select all the options having a value that matches with the argument.

Syntax−

sel = Select (driver.find_element_by_id ("name"))
sel.select_by_value ('Value')
  • select_by_index (arg) – Tit shall select an option that matches with the argument. The index begins from zero.

Syntax−

sel = Select (driver.find_element_by_id ("name"))
sel.select_by_index (1)
  • deselect_by_visible_text (arg) – it shall deselect all the options which displayed text matches with the argument.

Syntax−

sel = Select (driver.find_element_by_id ("name"))
sel.deselect_by_visible_text ('Visible Text')
  • deselect_by_value (arg) – it shall deselect all the options having a value that matches with the argument.

Syntax−

sel = Select (driver.find_element_by_id ("name"))
sel.deselect_by_value ('Value')
  • deselect_by_index(arg) – it shall deselect that matches with the argument. The index begins from zero.

Syntax−

sel = Select(driver.find_element_by_id ("name"))
sel.deselect_by_index(1)
  • all_selected_options – it shall yield all the options which are selected for a dropdown.
  • first_selected_option - it shall yield the first selected option for a multiselect dropdown or the currently selected option in a normal dropdown.
  • options - it shall yield all the options available under the select tagname.
  • deselect_all - it shall clear all the selected options in a multi-select dropdown.

Example

Code Implementation

from selenium import webdriver
from selenium.webdriver.support.select import Select
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(5)
#url launch
driver.get("https://the-internet.herokuapp.com/dropdown")
#object of Select
s= Select(driver.find_element_by_id("dropdown"))
#select option by value
s.select_by_value("1")

Output

raja
Published on 19-Nov-2021 11:03:24
Advertisements