Selenium WebDriver enables developers to automate browser interactions programmatically, simulating real user behavior. This powerful framework supports all major browsers and provides comprehensive APIs for clicking, typing, form submissions, drag-and-drop operations, and complex user workflows.
Setup and Installation
Python Setup
Install Selenium and WebDriver Manager for automatic driver management:
pip install selenium webdriver-manager
JavaScript Setup
Install the Selenium WebDriver package for Node.js:
npm install selenium-webdriver
Python Examples
Basic Interactions
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
# Setup driver with automatic driver management
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
wait = WebDriverWait(driver, 10)
try:
# Navigate to website
driver.get("https://example.com")
# Find and interact with elements
search_input = wait.until(EC.presence_of_element_located((By.NAME, "search")))
search_input.send_keys("selenium tutorial")
search_input.send_keys(Keys.RETURN)
# Click buttons
submit_button = wait.until(EC.element_to_be_clickable((By.ID, "submit-btn")))
submit_button.click()
finally:
driver.quit()
Form Handling
from selenium.webdriver.support.ui import Select
# Text inputs
username_field = driver.find_element(By.NAME, "username")
username_field.clear() # Clear existing text
username_field.send_keys("john_doe")
# Password fields
password_field = driver.find_element(By.NAME, "password")
password_field.send_keys("secure_password")
# Dropdown selections
dropdown = Select(driver.find_element(By.NAME, "country"))
dropdown.select_by_visible_text("United States")
dropdown.select_by_value("us")
dropdown.select_by_index(1)
# Checkboxes and radio buttons
checkbox = driver.find_element(By.ID, "agree-terms")
if not checkbox.is_selected():
checkbox.click()
# Submit form
form = driver.find_element(By.TAG_NAME, "form")
form.submit()
Advanced Interactions with ActionChains
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
# Hover over element
element = driver.find_element(By.CLASS_NAME, "menu-item")
actions.move_to_element(element).perform()
# Right-click (context menu)
actions.context_click(element).perform()
# Drag and drop
source = driver.find_element(By.ID, "source")
target = driver.find_element(By.ID, "target")
actions.drag_and_drop(source, target).perform()
# Complex mouse actions
actions.move_to_element(element)\
.click_and_hold()\
.move_by_offset(100, 50)\
.release()\
.perform()
# Keyboard shortcuts
actions.key_down(Keys.CONTROL)\
.send_keys('a')\
.key_up(Keys.CONTROL)\
.perform()
JavaScript Examples
Basic Interactions
const { Builder, By, Key, until, Select } = require('selenium-webdriver');
async function automateWebsite() {
const driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to website
await driver.get('https://example.com');
// Wait for elements
const searchInput = await driver.wait(
until.elementLocated(By.name('search')),
10000
);
// Type and submit
await searchInput.sendKeys('selenium automation');
await searchInput.sendKeys(Key.RETURN);
// Click buttons
const submitBtn = await driver.wait(
until.elementIsEnabled(By.id('submit-btn')),
5000
);
await submitBtn.click();
} finally {
await driver.quit();
}
}
automateWebsite();
Form Automation
async function fillForm(driver) {
// Text inputs
const usernameField = await driver.findElement(By.name('username'));
await usernameField.clear();
await usernameField.sendKeys('john_doe');
// Dropdown selection
const countryDropdown = await driver.findElement(By.name('country'));
const select = new Select(countryDropdown);
await select.selectByVisibleText('United States');
// Checkbox interaction
const checkbox = await driver.findElement(By.id('newsletter'));
const isSelected = await checkbox.isSelected();
if (!isSelected) {
await checkbox.click();
}
// Submit form
const form = await driver.findElement(By.css('form'));
await form.submit();
}
Advanced Mouse and Keyboard Actions
async function performAdvancedActions(driver) {
const actions = driver.actions();
// Hover over element
const menuItem = await driver.findElement(By.className('menu-item'));
await actions.move({ origin: menuItem }).perform();
// Drag and drop
const source = await driver.findElement(By.id('draggable'));
const target = await driver.findElement(By.id('droppable'));
await actions.dragAndDrop(source, target).perform();
// Keyboard shortcuts
await actions.keyDown(Key.CONTROL)
.sendKeys('a')
.keyUp(Key.CONTROL)
.perform();
// Complex mouse gestures
await actions.move({ origin: source })
.press()
.move({ x: 100, y: 50 })
.release()
.perform();
}
Best Practices
Wait Strategies
Always use explicit waits instead of implicit waits or sleep statements:
# Good: Explicit wait
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "button"))
)
# Bad: Sleep
time.sleep(5) # Don't do this
Error Handling
from selenium.common.exceptions import TimeoutException, NoSuchElementException
try:
element = wait.until(EC.presence_of_element_located((By.ID, "my-element")))
element.click()
except TimeoutException:
print("Element not found within timeout period")
except NoSuchElementException:
print("Element does not exist")
Resource Management
Always properly close the driver:
try:
# Your automation code
pass
finally:
driver.quit() # Always quit the driver
Common Use Cases
- Web Testing: Automated testing of web applications
- Form Automation: Filling out repetitive forms
- Data Extraction: Navigating and scraping dynamic content
- UI Testing: Validating user interface behavior
- Load Testing: Simulating multiple user interactions
Selenium's extensive API allows for virtually any user interaction simulation, making it an essential tool for web automation and testing workflows.