Selenium best practices come down to three habits: wait for a condition instead of a fixed time, find elements with locators that survive a redesign, and keep every test independent so it can run in parallel. In current Selenium 4 that means letting Selenium Manager fetch your drivers, using explicit waits and never mixing them with implicit ones, keeping assertions out of page objects, and creating test state through an API. When a suite passes locally and fails in CI, check those rules first.
The version facts on this page are for Selenium 4.52.0, released 29 October 2026 (checked 11 Nov 2026). Code is Python. Every rule maps one-to-one onto Java, C#, Ruby and JavaScript.
One thing before the list. The Selenium project deliberately avoids the phrase "best practices" in its own docs, on the grounds that no single approach fits every situation. That's why each rule below carries a verdict line saying when it applies.
Selenium best practices at a glance
| # | Practice | Why it matters | Common mistake |
|---|---|---|---|
| 1 | Let Selenium Manager handle drivers, pin the Selenium version | Driver and browser versions drift apart on CI runners | Still installing webdriver_manager or a hand-downloaded chromedriver |
| 2 | Wait for a condition with explicit waits | Timing races are a primary cause of flaky tests | time.sleep(3) before a click |
| 3 | Never mix implicit and explicit waits | Mixed waits produce timeouts nobody can predict | A global implicitly_wait(10) under every WebDriverWait |
| 4 | Locate by stable ID or test ID, then CSS, XPath last | Locators are what breaks when the front end is refactored | Absolute XPath copied from DevTools |
| 5 | Page objects own locators and actions, tests own assertions | One place to fix when a page changes, and tests stay readable | assert statements inside page classes |
| 6 | Model repeated widgets as components | The navbar changes once, so the fix should happen once | The same menu locators pasted into ten page objects |
| 7 | Create test state through an API | Logging in through the UI before every test is slow and fragile | Every test starts by filling in the login form |
| 8 | Keep tests independent, one fresh browser each | Parallel runs expose any shared state immediately | Test B relies on the order Test A created |
| 9 | Build drivers in one factory, driven by config | Browser, headless mode and Grid switch without code changes | webdriver.Chrome() scattered across fixtures |
| 10 | Run in parallel on Selenium Grid | Serial runs get slow enough that developers stop waiting | Turning on parallelism before fixing rule 8 |
| 11 | Make CI and local the same environment | Browser version, viewport and timezone drift make CI fail where local passes | Different browser versions locally and in the pipeline |
| 12 | Leave out what Selenium is bad at | Captchas, 2FA, email logins and performance checks are flaky by design | Automating a third-party login through its UI |
The practices, one by one
1. Let Selenium Manager handle drivers
Do this when: you're on Selenium 4.6 or later.
Selenium Manager is the project's own driver manager. It has shipped with every release since 4.6, and since 4.11 it can download the browser as well (Chrome from 4.11, Firefox from 4.12, Edge from 4.14). It only steps in when you have not provided a driver yourself, so the simplest setup is also the right one:
from selenium import webdriver
driver = webdriver.Chrome() # Selenium Manager finds or downloads a matching chromedriver
Older guides, including the first version of this one, used the third-party webdriver_manager package. You can delete it. What you should still do is pin the Selenium version in requirements.txt or your build file, so a new release does not land in the middle of a sprint.
2. Wait for a condition, never a clock
Do this when: anything on the page appears, changes or becomes clickable after something asynchronous. That's most of a modern app.
time.sleep(3) is a guess. Long enough on your laptop, too short on a loaded CI runner, and wasted time everywhere else. Selenium's waits documentation calls these race conditions "one of the primary causes of flaky tests".
An explicit wait polls until a specific condition holds, then moves on:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, timeout=10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-testid='login-button']"))).click()
Pick the condition that matches what the user needs. Presence in the DOM is not the same as visible, and visible is not the same as clickable. An "element not interactable" error often means you waited for the wrong one.
If you need a custom polling interval or want to ignore certain exceptions while waiting (what Java calls a FluentWait), Python does it with the same class: WebDriverWait(driver, timeout=10, poll_frequency=0.2, ignored_exceptions=[ElementNotInteractableException]). Reach for that only when the default polling actually causes a problem.
3. Never mix implicit and explicit waits
No exceptions on this one. Leave the implicit wait at its default and use explicit waits only.
An implicit wait is a global session setting that applies to every element lookup, and its default is 0. The original version of this guide suggested setting one for stable UIs. Don't. Selenium's docs carry a warning against mixing the two, with a worked example: an implicit wait of 10 seconds and an explicit wait of 15 seconds can produce a timeout after 20 seconds.
In an older suite the implicit wait can predate everyone on the team, and the explicit waits were added around it later. A failing step then hangs for a time you can't work out from the code. If you inherit a suite like that, remove the implicit wait first and fix whatever breaks. The list of things that break is the list of places your waits were already wrong. Our Playwright vs Selenium comparison goes into how the two tools differ on waiting, if you're weighing a switch.
4. Locate by stable ID or test ID, then CSS, XPath last
Do this when: writing any new locator, and when a locator has broken twice.
Selenium's locator guidance prefers HTML IDs when they're unique and predictable, then a well-written CSS selector. XPath works, but the docs call it hard to debug and slow. In practice the order that holds up best is:
- A unique, stable
id. - A dedicated test attribute agreed with the developers, such as
data-testid="login-button". This is the one to ask for. - Semantic attributes the product already needs, like
aria-labelorname. - Short CSS on stable class names.
- Relative XPath, when you truly need to match on text or walk up the tree.
Never an absolute path like /html/body/div[2]/div/form/button. It encodes the whole page structure, so any wrapper div added anywhere breaks it.
Keep locators short. The less of the DOM a locator describes, the fewer refactors it has to survive.
5. Page objects own locators and actions, tests own assertions
Do this when: more than two or three tests touch the same page.
The Page Object Model puts each page's locators and actions in one class, so a changed button gets fixed in one place. The rule people miss is in the same docs: page objects should never make verifications or assertions. The single exception is checking that the page and its critical elements have loaded.
class LoginPage:
path = "/login"
username = (By.ID, "username")
password = (By.ID, "password")
submit = (By.CSS_SELECTOR, "[data-testid='login-button']")
def __init__(self, driver, base_url):
self.driver, self.base_url = driver, base_url
self.wait = WebDriverWait(driver, 10)
def open(self):
self.driver.get(self.base_url + self.path)
self.wait.until(EC.visibility_of_element_located(self.username)) # the one allowed check
return self
def log_in_as(self, user, pw):
self.driver.find_element(*self.username).send_keys(user)
self.driver.find_element(*self.password).send_keys(pw)
self.driver.find_element(*self.submit).click()
return DashboardPage(self.driver, self.base_url)
The test then reads as intent: assert LoginPage(driver, url).open().log_in_as("admin", pw).greeting() == "Welcome, admin". Returning the next page object from an action gives you that fluent style for free. Page Factory annotations (@FindBy in Java) are an older way to wire up the same thing; plain classes with locator tuples are easier to debug.
6. Model repeated widgets as components
Worth doing once the same navbar, card or modal shows up on three or more pages.
Pull it into its own class and compose it into the page objects that contain it. DashboardPage(...).navbar.go_to_profile() is one line in the test, and a redesigned navbar is one class to fix. The component's locators live in the component class, next to its actions.
7. Create test state through an API
Do this when: a test needs a logged-in user or existing data before it starts.
Selenium's own guidance on generating application state is direct: don't use Selenium to prepare a test. Log in through an API, set the cookie, and start on the page you're testing.
import requests
resp = requests.post(f"{base_url}/api/login", json={"user": "admin", "password": pw})
driver.get(base_url) # you must be on the domain before you can set its cookie
driver.add_cookie({"name": "session", "value": resp.cookies["session"]})
driver.get(f"{base_url}/dashboard")
Same for data. Create the order or the project through the API, then drive only the part of the UI the test is about. For inputs that vary, use pytest.mark.parametrize to run one flow over several data sets, and a small builder for objects with many fields: set the three fields the test cares about and let defaults cover the other twenty-two.
There's a trade-off. Data created behind the UI's back can look different from data a user creates, so keep at least one test that builds its data through the UI the way a user would.
8. Keep tests independent, one fresh browser each
Do this when: you're about to turn on parallel runs. Not after.
Selenium's docs make this point on two pages, avoid sharing state and start a fresh browser per test. Each test creates its own data, gets its own WebDriver instance and does not care what ran before it. Selenium's own example of the wrong way, on its test independency page, is one test that publishes content and a second that checks the published module. The second depends on the first and on sync timing.
The tell that you've broken this rule: tests pass alone and fail together, or pass in one order and fail in another.
9. Build drivers in one factory, driven by config
Do this when: you run on more than one browser, or both locally and in CI.
One function decides which browser, headless or not, local or Grid. Tests never call webdriver.Chrome() directly.
import os
from selenium import webdriver
def make_driver():
browser = os.getenv("BROWSER", "chrome")
options = webdriver.ChromeOptions() if browser == "chrome" else webdriver.FirefoxOptions()
if os.getenv("HEADLESS", "1") == "1":
options.add_argument("--headless=new" if browser == "chrome" else "-headless")
grid_url = os.getenv("GRID_URL")
if grid_url:
driver = webdriver.Remote(command_executor=grid_url, options=options)
elif browser == "chrome":
driver = webdriver.Chrome(options=options)
else:
driver = webdriver.Firefox(options=options)
driver.set_window_size(1366, 768) # same viewport everywhere
return driver
Wrap it in a pytest fixture that quits the driver in teardown, and the fresh-browser rule from practice 8 comes along for free.
10. Run in parallel on Selenium Grid
Do this when: the suite takes longer than your developers are willing to wait for it, and you've already cut the tests that no longer earn their place.
Selenium Grid routes WebDriver commands to remote browsers. It's built for parallel runs across machines, different browser versions and different platforms. The quickest start is standalone mode, one process on one machine, listening on https://qa.tech:
java -jar selenium-server-4.52.0.jar standalone
GRID_URL=https://qa.tech pytest -n 4 # pytest-xdist runs four workers
The arithmetic is simple. As an illustration: 150 tests at about a minute each is 150 minutes run one after another. Spread across ten nodes, that's roughly 15 minutes. (The first version of this guide said "a few minutes". Fifteen is closer, before you also make the tests faster.)
Grid also covers the cross-browser case. Selenium drives Chrome, Edge and Firefox, and Safari through the safaridriver that ships with macOS. Parametrize the browser in your factory and the same test runs on each.
11. Make CI and local the same environment
Do this when: a test passes on your machine and fails in the pipeline.
Run the browser in a container with a pinned version, both locally and in CI. The Selenium project points to Docker images for running Grid with the common browsers, and its Grid getting-started docs list standalone mode as an easy Grid to set up in GitHub Actions or Jenkins. Fix the viewport, the timezone and the locale while you're at it. When the environment is identical, a red that only appears in CI is telling you something about timing or load, which narrows the search a lot.
Which CI/CD tools work best with Selenium UI tests? Any of them. GitHub Actions, GitLab CI, Jenkins and CircleCI all run a container and a test command equally well. The environment matters far more than the CI vendor.
12. Leave out what Selenium is bad at
This applies to any test that touches something you don't own.
Selenium publishes a list of discouraged behaviours: captchas, file downloads, HTTP response codes, Gmail, email and Facebook logins, test dependency, performance testing, link spidering and two-factor authentication. Each one is either impossible to automate reliably through a browser or better checked another way. Pair that with mocking external services, and a whole category of red runs disappears from your board.
What changed in Selenium since this guide first ran
Corrections to the March 2026 version, checked against the Selenium docs on 11 Nov 2026:
- Drivers. Use Selenium Manager (practice 1). The
webdriver_managerimports in the old Grid example are unnecessary. - Implicit waits. The old advice to set one "for very stable UIs" contradicts the official warning (practice 3).
- Grid version. The old command started
selenium-server-4.35.0.jar. The current server is 4.52.0.
And one direction of travel. Selenium is moving its whole implementation from WebDriver Classic to WebDriver BiDi, the W3C bidirectional protocol the project created with the browser vendors, while keeping backwards compatibility where it can. Its docs describe CDP support as temporary until BiDi is in place. BiDi is opt-in today (options.enable_bidi = True in Python), and it's where console-log and network capture are heading. Try it on one test before you plan any suite changes around it.
What Selenium best practices can't fix
Follow all twelve and you'll have a faster, quieter suite. The timeouts, stale elements and parallel collisions mostly stop. That's the noisy kind of flakiness, and we've written about why the other kind of flaky test is worth keeping.
Selenium is free and open source, it runs on hardware you control, it has official bindings for Java, Python, C#, Ruby and JavaScript, it drives real Chrome, Edge, Firefox and Safari, and a scripted check does exactly the same steps every run. For a check that must behave identically every time, that determinism is the point. If your team already has a setup that works, there's no reason to rip it out.
Two jobs stay with people, though.
The first is maintenance. Page objects make a changed button cheap to fix, but someone still fixes it, and a suite left alone tends to grow until it holds more regression tests than anyone can comfortably maintain.
The second is deciding what to test at all. A script only checks what somebody thought to assert. Add an item to the cart, assert the badge says 1, pass. The cart page behind that badge could be showing last week's price and the test would never know.
The newer way moves most of both jobs off people. A context-based testing agent learns the product, reads what a pull request changed, works out which flows that change could reach and checks them on the preview. QA.tech is an AI testing platform built on that idea. It crawls your app into a knowledge graph before it tests anything, and on each pull request it reads the pull request and its diff, then runs against the preview deployment. A checkout change gets more depth than a settings tweak. Tests are goals written in plain English. Pages are read through a combination of the DOM and visual models, so there are no selectors for anyone to write, and a renamed button or a moved layout doesn't break the test. When a flow changes on purpose, the test still needs updating, in plain English. The verdict on the PR is pass, fail or "unable to verify". The screenshots, network and console logs, and the session recording where one was captured, stay in the run for whoever wants to check them.
That's also the sense in which it's faster than Selenium. Covering a new flow starts with a sentence describing it; the agent drafts the steps, runs them once, and you review the draft before it joins the suite. In Selenium the same flow is a page object and three locators before the first run. A Selenium run is still quicker to execute, and the agent's run will not be byte-identical every time; it's repeatable on unchanged pages and adapts when the UI changes.
Web tests run in Chromium only, so real Safari and Firefox stay a Selenium job, and nothing converts an existing Selenium suite into agent tests.
In practice that's two layers, and you may already own the first. The Selenium tests that guard sign-up and payment go on running on a schedule, written to the practices above. Whatever a given pull request touches goes to PR testing, and the rest of the scripted suite shrinks as that coverage takes over. If you're deciding whether to move off Selenium at all, our Selenium alternatives page compares six frameworks on what each still leaves you maintaining.
FAQ
What are the most important Selenium WebDriver best practices?
Use explicit waits on specific conditions and never time.sleep. Do not mix implicit and explicit waits. Locate elements by stable IDs or dedicated test attributes before CSS, with XPath last. Keep locators in page objects and assertions in tests. Create test data through an API, give every test its own browser, and run in parallel on Selenium Grid in the same containerised environment locally and in CI.
Should I use implicit or explicit waits in Selenium?
Explicit waits. An implicit wait is a global session setting with a default of 0, and the Selenium waits documentation warns against combining it with explicit waits because the result is unpredictable: a 10-second implicit wait plus a 15-second explicit wait can time out after 20 seconds. Leave the implicit wait at 0 and wait for the exact condition each step needs.
Do I still need WebDriverManager or a downloaded chromedriver in Selenium 4?
No. Selenium Manager has shipped with every Selenium release since 4.6, and from 4.11 (Chrome) to 4.14 (Edge) it also manages the browsers themselves. If you do not provide a driver, it finds or downloads a matching one. Remove third-party driver managers and pin your Selenium version instead.
Should page objects contain assertions?
No, with one exception. Selenium's Page Object Model guidance says page objects should never make verifications or assertions, apart from checking that the page and its critical elements loaded. Page objects expose actions and state; the test decides what is correct.
Why do my Selenium tests pass locally but fail in CI?
Check three causes first: a fixed sleep or wrong wait condition that's too short on a slower CI runner, tests that share data and collide when they run in parallel, or a different browser version and viewport in the pipeline. Switch to explicit waits, isolate every test, and run the same pinned browser in a container in both places.
Which locator is best in Selenium?
A unique, stable ID, or a dedicated test attribute such as data-testid agreed with your developers. After that, a short CSS selector. Selenium's docs describe XPath as harder to debug and slower, so keep it for cases that need text matching or walking up the DOM, and never use absolute XPath paths.
Is Selenium still worth using in 2026?
Yes, for the right job. Selenium is actively maintained, with 4.52.0 released on 29 October 2026, and it is moving to the W3C WebDriver BiDi protocol. It is a strong choice when you need real Safari, several programming languages or tests on your own infrastructure. For a new Chromium-first web project, compare it with a framework that has auto-waiting built in before you commit.
