How to Automate Testing with Selenium: A Step-by-Step Guide
Selenium is a powerful open-source framework for automating browser testing. It supports multiple programming languages, including Python, Java, and JavaScript, allowing teams to verify web applications across different browsers with minimal manual effort. This tutorial walks you through the fundamentals of setting up Selenium and writing your first automated test.
Python is recommended for beginners because of its simple syntax and excellent Selenium support. Make sure Python and pip are installed on your system before you begin.
1. Install Selenium and WebDriver
Open your terminal and run:
pip install selenium
Next, download the appropriate WebDriver for your main browser. For Chrome, get ChromeDriver; for Firefox, get geckodriver. Place the executable in your project folder or system PATH.
2. Write Your First Test Script
Create a file named test_demo.py and add the following:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
assert "Example Domain" in driver.title
driver.quit()
This simple script launches a browser, navigates to a URL, validates the page title, and closes the session.
3. Interact with Elements and Handle Waits
Use locators like ID, class name, or CSS selectors to interact with page elements:
driver.find_element(By.ID, "search").send_keys("Selenium")
driver.find_element(By.CLASS_NAME, "submit").click()
Add explicit waits to handle dynamic content and prevent flaky tests:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "submit")))
4. Integrate with Testing and CI/CD Frameworks
Combine Selenium with pytest or JUnit to generate structured reports and organize test cases. Integrate your suite into CI/CD tools like Jenkins or GitHub Actions so tests run automatically on every code commit.
Conclusion: Automating web tests with Selenium saves time and improves product quality. Start by automating one critical user flow, then gradually expand your coverage as you gain confidence.