Randomly Select Dropdown Option with Selenium

  • Share this:

Code introduction


This function uses the Selenium library to randomly select an option from a dropdown specified by its ID.


Technology Stack : Selenium, Select, By, WebDriverWait, expected_conditions

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_select_option_from_dropdown(driver, dropdown_id):
    from selenium.webdriver.support.ui import Select
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    # Wait for the dropdown to be clickable
    dropdown = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, dropdown_id)))
    # Click on the dropdown
    dropdown.click()
    # Find all options within the dropdown
    options = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, ".//option")))
    # Select a random option from the dropdown
    selected_option = options[random.randint(0, len(options) - 1)]
    # Click on the selected option
    selected_option.click()