Random Element Selection and Click with Selenium WebDriver

  • Share this:

Code introduction


This function uses Selenium WebDriver to select a random element from the list of elements found by the given ID and click on it.


Technology Stack : Selenium WebDriver, random.choice

Code Type : Function

Code Difficulty : Intermediate


                
                    
def select_random_element_by_id(driver, element_id):
    """
    Selects a random element from a list of elements found by the given ID.
    
    Args:
        driver (WebDriver): The Selenium WebDriver instance.
        element_id (str): The ID of the element to find.
    """
    elements = driver.find_elements_by_id(element_id)
    if elements:
        import random
        selected_element = random.choice(elements)
        selected_element.click()

# JSON Explanation