To perform operations on DropDown we should use locators and objects of select class.
Select class contains three methods and one property to perform action on dropdowns.
This method is used to select the option in dropdown using index value. It takes integer value as argument and it doesn’t return anything.
dd_options.select_by_index(2)
This method is used to select the option in dropdown using value of dropdown in select tag. It takes string value as argument and it doesn’t return anything.
dd_options.select_by_value("OptionThree")
This method is used to select the option in dropdown using text value. It takes string value as argument and it doesn’t return anything.
dd_options.select_by_visible_text("Option5")
This method is used to get all the options of dropdown.It doesn’t take any argument but returns list objects.
# List the values in Drop Down
dd_v = dd_options.options
for dd_values in dd_v:
print(dd_values.text)
from selenium import webdriver
ele = wait.until(ec.presence_of_element_located((By.ID,"dropdown"))) dd_options = Select(ele)
dd_options.select_by_visible_text("Option5")
Handling_DropDown.py
from selenium import webdriver
import time
from selenium.common.exceptions import ElementNotVisibleException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
# 1. import the Select class
from selenium.webdriver.support.select import Select
driver = webdriver.Chrome("/Users/admin/Documents/Skill2Lead/Others/drivers/chromedriver.exe")
driver.get("http://www.dummypoint.com/seleniumtemplate.html")
time.sleep(2)
wait = WebDriverWait(driver,25,poll_frequency=1,ignored_exceptions=[ElementNotVisibleException,NoSuchElementException])
ele = wait.until(ec.presence_of_element_located((By.ID,"dropdown")))
ele.click()
# 2. Create the object for Select class
dd_options = Select(ele)
# 3. List the values in Drop Down
dd_v = dd_options.options
for dd_values in dd_v:
print(dd_values.text)
# 4. Click by Index
dd_options.select_by_index(2)
time.sleep(2)
# Click by Value
dd_options.select_by_value("OptionThree")
time.sleep(2)
# Click by Text
dd_options.select_by_visible_text("Option5")
time.sleep(5)
driver.quit()