Handle Dynamic Dropdown in Selenium Python

Profile picture for user arilio666

To handle dynamic dropdowns using Python in Selenium, you must first identify the element that triggers the dropdown options and then select the required option among the created possibilities.

Handle Dynamic Dropdown in Selenium Python

Let us use this site to select "Austria."

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium. web driver.support.UI import WebDriverWait
from selenium. web driver.support import expected_conditions as EC


driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

driver.maximize_window()
driver.get('http://autopract.com/selenium/dropdown4/')
dropdown_trigger = WebDriverWait(driver, 10).until(
   EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[title="Afghanistan"]'))
)
dropdown_trigger.click()
dropdown_options = WebDriverWait(driver, 10).until(
   EC.visibility_of_all_elements_located((By.XPATH, '//ul[@role="listbox"]/li'))
)
for option in dropdown_options:
   if option.text == "Austria":  
       option.click()
       break
  • We begin by visiting the webpage that has the dynamic dropdown. 
  • Then, we use WebDriverWait and the element_to_be_clickable condition to wait for the element that triggers the dropdown to be clickable. 
  • We click on the trigger element to display the dropdown options once it is clickable.
  • Then, we use visibility_of_all_elements_located to wait for the dynamic dropdown options to become visible. 
  • This will give list of all the dropdown menu options. 
  • Then we loop through the alternatives, checking whether the desired option text matches the current option. 
  • If it does, we select that option to exit the loop.