Building a Web Automation Testing Framework with Python and Selenium
Selenium is a widely used tool for autoamting web browser interactions, enabling the creation of efficient testing frameworks. This guide covers setting up a basic framework using Python and Selenium.
Installation and Setup
Install Selenium using pip:
pip install selenium
Download and configure a browser driver, such as geckodriver for Firefox. Extract and move it to a directory in your system's PATH.
Basic Browser Operations
Create a Python script to perform common browser actions:
import time
from selenium import webdriver
# Initialize Firefox driver
browser = webdriver.Firefox()
# Navigate to a website
browser.get('https://www.example.com')
# Adjust window dimensions
browser.set_window_size(1024, 768)
# Wait for 2 seconds
time.sleep(2)
# Refresh the page
browser.refresh()
# Maximize the window
browser.maximize_window()
# Close the browser
browser.quit()
Element Interaction and Testing
Automate interactions with web elements, such as input fields and buttons:
import time
from selenium import webdriver
# Start browser session
driver = webdriver.Firefox()
driver.get('https://www.testforum.com/login')
# Wait for page load
time.sleep(3)
# Locate and fill username field using ID
username_field = driver.find_element_by_id('username_input')
username_field.send_keys('test_user')
# Locate and fill password field using ID
password_field = driver.find_element_by_id('password_input')
password_field.send_keys('secure_pass')
# Locate login button using XPath and click
login_button = driver.find_element_by_xpath('//button[@type="submit"]')
login_button.click()
# Retrieve and print button text
button_text = login_button.text
print(f'Button text: {button_text}')
# Get attribute value
type_attr = login_button.get_attribute('type')
print(f'Button type attribute: {type_attr}')
# Close the session
driver.quit()
This framework supports regression testing by automating repetitive tasks, reducing manual effort and improving test coevrage.