Randomly Click #Click Me# Button on Web Page with Selenium

  • Share this:

Code introduction


This function uses the Selenium library to randomly click a button on a web page that contains the text 'Click Me'.


Technology Stack : Selenium, Python, WebDriverWait, expected_conditions

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def click_random_button(driver):
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    try:
        # Wait for a random button to be clickable and then click it
        random_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Click Me')]"))
        )
        random_button.click()
    except Exception as e:
        print(f"An error occurred: {e}")