Random Selection of Web Elements using Selenium WebDriver

  • Share this:

Code introduction


This function uses the Selenium WebDriver to find all elements on the page that match a given identifier, then randomly selects one element and waits for it to become clickable.


Technology Stack : Selenium, WebDriver, CSS Selector, XPath, WebDriverWait, expected_conditions, random

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_select_element(driver, element_identifier):
    """
    This function selects a random element from a list of elements identified by a given identifier.
    
    Args:
        driver (WebDriver): The Selenium WebDriver instance.
        element_identifier (str): The CSS selector or XPath expression to identify the elements.
    """
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # Find all elements matching the given identifier
    elements = driver.find_elements(By.CSS_SELECTOR, element_identifier)
    
    # Select a random element if there are any elements found
    if elements:
        import random
        selected_element = random.choice(elements)
        # Wait for the selected element to be clickable
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, element_identifier)))
        return selected_element
    else:
        return None