惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
IT之家
IT之家
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
C
Check Point Blog
T
Tailwind CSS Blog
博客园 - Franky
H
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
J
Java Code Geeks
腾讯CDC
罗磊的独立博客
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
Martin Fowler
Martin Fowler
酷 壳 – CoolShell
酷 壳 – CoolShell
I
InfoQ
B
Blog
V
Visual Studio Blog
F
Fortinet All Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
🧪 Selenium with Python: A Practical Cheat Sheet for Moder...
Gayathri · 2026-04-25 · via DEV Community

If you’re a QA engineer stepping into automation — or an SDET who just needs a quick refresher — this cheat sheet covers the Selenium + Python essentials you actually use at work.

No theory overload. No outdated patterns. Just practical examples you can copy, adapt, and scale.

Thanks for reading! Subscribe for free to receive new posts and support my work.

✅ Setup & Installation

Install Selenium:

pip install selenium

Make sure the correct browser driver is available in your system PATH:

Chrome → chromedriver

Firefox → geckodriver

Edge → msedgedriver

🚀 Starting the Browser

Launch Chrome
from selenium import webdriver

driver = webdriver.Chrome()

driver.get(”https://example.com”)

Headless Mode (Recommended for CI)

from selenium.webdriver.chrome.options import Options

options = Options()

options.add_argument(”--headless”)

options.add_argument(”--window-size=1920,1080”)

driver = webdriver.Chrome(options=options)

🔍 Locating Elements (The Most Important Skill)

Always prioritize reliable, stable locators.

from selenium.webdriver.common.by import By

Preferred Locators
driver.find_element(By.ID, “submit”)

driver.find_element(By.NAME, “email”)

driver.find_element(By.CSS_SELECTOR, “.login-button”)

driver.find_element(By.CSS_SELECTOR, “input[type=’password’]”)

XPath (Use Sparingly)

driver.find_element(By.XPATH, “//button[text()=’Login’]”)

✅ Tip: If your tests break often, your locators are probably the problem.

✍️ User Interactions

element.click()
element.send_keys(”user@test.com”)
element.clear()
Read values:
element.text
element.get_attribute(”value”)

⏳ Waiting for Elements (Non‑Negotiable)

Explicit Waits (Best Practice)
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
login_btn = wait.until(
EC.element_to_be_clickable((By.ID, “login”))
)

Common conditions:

EC.presence_of_element_located
EC.visibility_of_element_located
EC.element_to_be_clickable

❌ Avoid time.sleep() — it causes flaky tests.

📄 Forms & Dropdowns

from selenium.webdriver.support.ui import Select
dropdown = Select(driver.find_element(By.ID, “country”))
dropdown.select_by_visible_text(”India”)

🔔 Alerts, Frames & Windows

Alerts

alert = driver.switch_to.alert
alert.accept()

iFrames

driver.switch_to.frame(”frameName”)
driver.switch_to.default_content()

Multiple Tabs
driver.switch_to.window(driver.window_handles[1])

📜 Scrolling & JavaScript

driver.execute_script(”window.scrollTo(0, document.body.scrollHeight)”)
driver.execute_script(”arguments[0].scrollIntoView()”, element)

📷 Screenshots (For Failing Tests)

driver.save_screenshot(”failure.png”)
element.screenshot(”button.png”)

🧹 Cleanup
driver.close()
driver.quit()

🚀 Selenium + Pytest: Real‑World Automation Setup
Selenium alone isn’t enough. Pytest makes your automation scalable, readable, and CI‑ready.
**
✅ Install Pytest**

pip install pytest

🧱 Project Structure (Recommended)
tests/
├── pages/
│ └── login_page.py
├── conftest.py
├── test_login.py
└── pytest.ini

🔁 Pytest WebDriver Fixture

conftest.py
import pytest
from selenium import webdriver

@pytest.fixture
def driver():
driver = webdriver.Chrome()
driver.maximize_window()
yield driver
driver.quit()

✅ Automatically manages setup & teardown
✅ Cleaner than setUp() / tearDown()

🧪 Writing a Test

def test_valid_login(driver):
driver.get(”https://example.com/login”)
driver.find_element(By.ID, “username”).send_keys(”admin”)
driver.find_element(By.ID, “password”).send_keys(”password”)
driver.find_element(By.ID, “login”).click()
assert “Dashboard” in driver.title

🧠 Using Page Object Model with Pytest

pages/login_page.py

class LoginPage:
def init(self, driver):
self.driver = driver
def login(self, user, pwd):
self.driver.find_element(By.ID, “username”).send_keys(user)
self.driver.find_element(By.ID, “password”).send_keys(pwd)
self.driver.find_element(By.ID, “login”).click()

test_login.py

def test_login_success(driver):
page = LoginPage(driver)
page.login(”admin”, “password”)
assert “Dashboard” in driver.title

🏷️ Pytest Markers (Power Feature)

@pytest.mark.smoke
def test_smoke_login():
pass

Run specific tests:

pytest -m smoke

📊 HTML Reports (CI‑Friendly)

pip install pytest-html
pytest --html=report.html