Automating Web Interactions with Selenium

  • Share this:

Code introduction


The function uses the Selenium library to automate the process of opening a web page, waiting for a button element to be clickable and then clicking it, sending text to an input field, submitting the form, and finally closing the browser.


Technology Stack : Selenium, Chrome WebDriver, WebDriverWait, expected_conditions

Code Type : Function

Code Difficulty : Intermediate


                
                    
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def random_browser_action(url, timeout=10):
    # Initialize a Chrome WebDriver
    driver = webdriver.Chrome()
    
    # Navigate to the specified URL
    driver.get(url)
    
    # Wait for a specific element to be clickable and then click it
    element_to_click = WebDriverWait(driver, timeout).until(
        EC.element_to_be_clickable((By.ID, "button_to_click"))
    )
    element_to_click.click()
    
    # Send keys to an input field
    input_field = driver.find_element(By.ID, "input_field")
    input_field.send_keys("Hello, World!")
    
    # Submit the form
    submit_button = driver.find_element(By.ID, "submit_button")
    submit_button.click()
    
    # Close the browser
    driver.quit()