How to Automate Web Testing Using Selenium and Python
Automating web testing with Selenium and Python is a widely used approach in QA and development for verifying web application behavior. Below is a step-by-step guide to help you get started:
๐งช What is Selenium?
Selenium is an open-source tool that automates browsers. It supports all major browsers and platforms and is widely used for web UI testing.
๐ Prerequisites
✅ 1. Install Python
Download and install from: https://www.python.org/
✅ 2. Install Selenium
bash
Copy
Edit
pip install selenium
✅ 3. Install WebDriver
You need a browser driver that matches your browser:
Browser Driver
Chrome chromedriver
Firefox geckodriver
Ensure the driver is in your system’s PATH or specify the path directly in your script.
๐ Basic Example: Open a Website and Check Title
python
Copy
Edit
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# Initialize the Chrome driver
driver = webdriver.Chrome()
# Open a web page
driver.get("https://example.com")
# Wait for 3 seconds
time.sleep(3)
# Check the title
print("Page title is:", driver.title)
# Close the browser
driver.quit()
๐ Interacting with Web Elements
✅ Locating Elements
python
Copy
Edit
driver.find_element(By.ID, "element_id")
driver.find_element(By.NAME, "username")
driver.find_element(By.CLASS_NAME, "btn-primary")
driver.find_element(By.XPATH, "//input[@type='text']")
driver.find_element(By.CSS_SELECTOR, "div.container > a.link")
✅ Performing Actions
python
Copy
Edit
element = driver.find_element(By.NAME, "username")
element.send_keys("my_username")
driver.find_element(By.ID, "submit").click()
⏳ Handling Waits
Implicit Wait
python
Copy
Edit
driver.implicitly_wait(10) # seconds
Explicit Wait
python
Copy
Edit
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, "submit")))
๐ธ Take Screenshot
python
Copy
Edit
driver.save_screenshot("screenshot.png")
๐ Folder Structure (Recommended)
bash
Copy
Edit
/tests
├── test_login.py
├── test_search.py
/drivers
└── chromedriver
/utils
└── selenium_utils.py
✅ Best Practices
Use Page Object Model (POM) for cleaner, reusable code
Use unittest or pytest for test organization
Use headless browsers (options.add_argument("--headless")) for CI
Capture logs/screenshots on failure
Integrate with CI tools like GitHub Actions or Jenkins
Learn Selenium Python Training in Hyderabad
Read More
Python vs Other Languages for Selenium: Pros & Cons
Understanding the Role of WebDriver in Automation
Basic Selenium Commands Every Beginner Should Know
Writing Your First Selenium Script in Python
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment