Random Webdriver Actions with Selenium

  • Share this:

Code introduction


This function uses the Selenium library to randomly perform operations on a web page, such as clicking, typing, going back, forward, or refreshing. The function accepts a URL and an action type parameter and performs the corresponding web operation based on the action type.


Technology Stack : Selenium library, Chrome WebDriver, Options, Service, By, Keys, and other related Selenium components

Code Type : The type of code

Code Difficulty :


                
                    
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import random

def random_webdriver_action(url, action_type):
    # Initialize the Chrome WebDriver with options
    chrome_options = Options()
    chrome_options.add_argument("--headless")  # Run in headless mode
    service = Service(executable_path='path/to/chromedriver')  # Path to chromedriver

    # Create a new instance of the Chrome WebDriver
    driver = webdriver.Chrome(service=service, options=chrome_options)

    try:
        # Navigate to the specified URL
        driver.get(url)
        
        # Randomly select an action based on the action_type
        if action_type == "click":
            element = driver.find_element(By.TAG_NAME, "button")
            element.click()
        elif action_type == "send_keys":
            element = driver.find_element(By.ID, "username")
            element.send_keys("testuser")
        elif action_type == "back":
            driver.back()
        elif action_type == "forward":
            driver.forward()
        elif action_type == "refresh":
            driver.refresh()
        else:
            print("Invalid action type provided.")
    finally:
        # Close the browser window
        driver.quit()

# Example usage
random_webdriver_action("http://example.com", "click")