1. Setup
Installation:
pip install selenium
from selenium import webdriver
# Set the path to the WebDriver executable
driver = webdriver.Chrome(executable_path='path/to/chromedriver')
2. Basic Commands
- Open a URL:
driver.get("https://www.example.com")
- Get Title:
title = driver.title
- Get Current URL:
current_url = driver.current_url
- Close the Browser:
driver.quit() # or driver.close()
3. Locators
- By ID:
element = driver.find_element(By.ID, "elementId")
- By Name:
element = driver.find_element(By.NAME, "elementName")
- By Class Name:
element = driver.find_element(By.CLASS_NAME, "className")
- By CSS Selector:
element = driver.find_element(By.CSS_SELECTOR, "cssSelector")
- By XPath:
element = driver.find_element(By.XPATH, "//tag[@attribute='value']")
4. Interacting with Elements
- Clicking an Element:
element.click()
- Sending Keys:
element.send_keys("text")
- Getting Text:
text = element.text
- Getting Attribute Value:
value = element.get_attribute("attributeName")
- Checking Visibility:
is_displayed = element.is_displayed()
5. Waits
- Implicit Wait:
driver.implicitly_wait(10) # seconds
- Explicit Wait:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ECwait = WebDriverWait(driver, 10) element = wait.until(EC.visibility_of_element_located((By.ID, "elementId")))
6. Actions
- Mouse Hover:
from selenium.webdriver.common.action_chains import ActionChains actions = ActionChains(driver) actions.move_to_element(element).perform()
- Drag and Drop:
source = driver.find_element(By.ID, "sourceId") target = driver.find_element(By.ID, "targetId") actions.drag_and_drop(source, target).perform()
7. Handling Alerts
- Accept Alert:
alert = driver.switch_to.alert alert.accept()
- Dismiss Alert:
alert.dismiss()
- Get Alert Text:
alert_text = alert.text
8. Taking Screenshots
driver.save_screenshot("screenshot.png")
9. Example Test with pytest
import pytest
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 ECclass TestExample:
@pytest.fixture(scope="class")
def setup(self):
self.driver = webdriver.Chrome(executable_path='path/to/chromedriver')
yield # This allows the test to run
self.driver.quit()def test_example(self, setup):
self.driver.get("https://www.example.com")
assert "Example Domain" in self.driver.title
element = self.driver.find_element(By.CSS_SELECTOR, "h1")
assert element.text == "Example Domain"
10. Tips
- Browser Compatibility: Ensure the WebDriver version matches the browser version.
- Headless Mode: Run tests without opening a browser window:
options = webdriver.ChromeOptions() options.add_argument('--headless') driver = webdriver.Chrome(options=options)
- Page Object Model: Organize tests for better maintainability.