Handling DropDown

To perform operations on DropDown we should use locators and objects of select class.

DropDown

Select class contains three methods and one property to perform action on dropdowns.

  • select_by_index()
  • select_by_value()
  • select_by_visible_text()
  • options property



select_by_index() Method:

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)

select_by_value() Method:

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")


DropDown

select_by_visible_text() Method:

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")


DropDown

options property:

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)




To select options in dropdown we need to follow the below steps.

  • First import the select class.
  • from selenium import webdriver

  • Create the object for Select class and pass webelement object to Select class while creating object.
  •  
    ele = wait.until(ec.presence_of_element_located((By.ID,"dropdown")))
    dd_options = Select(ele)
    
  • Now call the method of select class to perform action.
  • 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()