How to retrieve all options in a dropdown using Selenium?

Rest AssuredSeleniumDynamic Programming

We can retrieve all options in a dropdown using Selenium. All the options in the dropdown are stored in a list data structure. This is achieved with the help of options() which is a method under the Select class.

options() returns a list of all options under the select tag. An empty list is returned if the dropdown is not identified on the page with the help of any of the locators.

Syntax

d = Select(driver.find_element_by_id("selection"))
o = d.options()

Example

Code Implementation for getting all options in the dropdown.

from selenium import webdriver
from selenium.webdriver.support.select import Select
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']"))

#store the options in a list with options method
l = d.options

#to count the number of options and print in console
print(len(l))

#to get all the number of options and print in console
for i in l:
print(i.text)

#to close the browser
driver.close()
raja
Updated on 19-Nov-2021 11:59:52

Advertisements