Python-Selenium Testing Guide
Introduction
Selenium is a powerful tool for controlling web browsers through programs and performing browser
automation. It is widely used for automating web applications for testing purposes.
Python, with its simplicity and extensive library support, is a popular language for writing Selenium test
scripts.
Setting Up Selenium in Python
1. Install Python (https://www.python.org/)
2. Install Selenium using pip:
pip install selenium
3. Download the appropriate WebDriver (e.g., ChromeDriver for Google Chrome)
https://sites.google.com/a/chromium.org/chromedriver/
Basic Selenium Script
from selenium import webdriver
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a website
driver.get("https://www.google.com")
Python-Selenium Testing Guide
# Interact with the page
search_box = driver.find_element("name", "q")
search_box.send_keys("Python Selenium")
search_box.submit()
# Close the browser
driver.quit()
Locating Elements
Selenium provides several methods to locate elements on a webpage:
- find_element(By.ID, "id")
- find_element(By.NAME, "name")
- find_element(By.CLASS_NAME, "classname")
- find_element(By.TAG_NAME, "tagname")
- find_element(By.LINK_TEXT, "linktext")
- find_element(By.PARTIAL_LINK_TEXT, "partiallink")
- find_element(By.CSS_SELECTOR, "css")
- find_element(By.XPATH, "xpath")
Common Operations
- Clicking an element: element.click()
Python-Selenium Testing Guide
- Entering text: element.send_keys("text")
- Clearing text: element.clear()
- Submitting forms: element.submit()
- Navigating: driver.back(), driver.forward(), driver.refresh()
Waits in Selenium
Selenium supports two types of waits:
1. Implicit Wait: driver.implicitly_wait(10)
2. Explicit Wait:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "someid")))
Best Practices
- Use page object model (POM) for maintainable test code.
- Keep WebDriver interactions minimal in tests, shift them to utility methods.
- Handle exceptions and take screenshots on failures.
- Clean up test data and close browsers properly.