Skip to content

Selenium

Selenium WebDriver is a tool for automating browser-based applications for testing purposes across multiple browsers and platforms.

Installation

# Python
pip install selenium

# Node.js
npm install selenium-webdriver

# Maven (Java)
# <dependency>
#   <groupId>org.seleniumhq.selenium</groupId>
#   <artifactId>selenium-java</artifactId>
#   <version>4.15.0</version>
# </dependency>

Basic Setup

Python

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

# Initialize driver
driver = webdriver.Chrome()
driver.get("https://example.com")

# Close browser
driver.quit()

Java

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TestExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");
        driver.quit();
    }
}

Finding Elements

MethodExample
IDfind_element(By.ID, "id_value")
Namefind_element(By.NAME, "name_value")
Classfind_element(By.CLASS_NAME, "class_value")
CSS Selectorfind_element(By.CSS_SELECTOR, "div.content")
XPathfind_element(By.XPATH, "//button[@id='submit']")
Link Textfind_element(By.LINK_TEXT, "Click Here")
Tag Namefind_element(By.TAG_NAME, "a")

Examples

# Find single element
element = driver.find_element(By.ID, "email")
elements = driver.find_elements(By.CLASS_NAME, "link")

# Using XPath
element = driver.find_element(By.XPATH, "//input[@type='email']")

# Using CSS Selector
element = driver.find_element(By.CSS_SELECTOR, "div#main > p.intro")

Interacting with Elements

# Click
element.click()

# Type text
element.send_keys("test@example.com")

# Clear text
element.clear()

# Submit form
element.submit()

# Get attribute
href = element.get_attribute("href")

# Get text
text = element.text

# Is displayed
if element.is_displayed():
    element.click()

# Is enabled
if element.is_enabled():
    element.send_keys("input")

Waits

Explicit Wait

wait = WebDriverWait(driver, 10)

# Wait for element to be clickable
element = wait.until(
    EC.element_to_be_clickable((By.ID, "submit"))
)
element.click()

# Wait for element visibility
element = wait.until(
    EC.visibility_of_element_located((By.ID, "message"))
)

Implicit Wait

driver.implicitly_wait(10)  # Wait 10 seconds
element = driver.find_element(By.ID, "email")
# Go to URL
driver.get("https://example.com")

# Back
driver.back()

# Forward
driver.forward()

# Refresh
driver.refresh()

# Get current URL
current_url = driver.current_url

# Get page title
title = driver.title

Form Handling

# Fill form
email_input = driver.find_element(By.NAME, "email")
email_input.send_keys("test@example.com")

password_input = driver.find_element(By.NAME, "password")
password_input.send_keys("password123")

# Submit
submit_button = driver.find_element(By.ID, "login")
submit_button.click()

# Or submit form directly
password_input.submit()
from selenium.webdriver.support.select import Select

dropdown = Select(driver.find_element(By.ID, "country"))

# Select by visible text
dropdown.select_by_visible_text("United States")

# Select by value
dropdown.select_by_value("US")

# Select by index
dropdown.select_by_index(0)

# Get all options
options = dropdown.options
for option in options:
    print(option.text)

Window & Tab Management

# Get current window handle
current_window = driver.current_window_handle

# Get all window handles
windows = driver.window_handles
driver.switch_to.window(windows[1])  # Switch to second tab

# Close current window
driver.close()

# Switch back
driver.switch_to.window(current_window)

Alerts

# Switch to alert
alert = driver.switch_to.alert

# Get alert text
text = alert.text

# Accept (OK)
alert.accept()

# Dismiss (Cancel)
alert.dismiss()

# Type text in prompt
alert.send_keys("input text")

Running Tests

Python unittest

# Run all tests
python -m unittest discover

# Run specific test file
python -m unittest tests.test_login

# Run specific test
python -m unittest tests.test_login.LoginTest.test_valid_login

# With verbosity
python -m unittest discover -v

Pytest

# Run all tests
pytest

# Run specific file
pytest tests/test_login.py

# Run specific test
pytest tests/test_login.py::test_valid_login

# With output
pytest -v
pytest -s  # Show print statements

Best Practices

  • Use explicit waits instead of implicit waits
  • Close browser after tests with driver.quit()
  • Use Page Object Model for maintainability
  • Handle exceptions with try/except
  • Wait for elements to be visible before interacting
  • Use descriptive test names
  • Clean up test data after tests
  • Run tests in headless mode for CI/CD

Resources


Last updated: 2025-07-06|Edit on GitHub