Selenium's Rules for AI Agents
Why This Matters
Language models learned Selenium from twenty years of examples on the internet, and most of those examples are old. Ask a general-purpose AI for a Selenium test and you will regularly get time.sleep(3), find_element_by_id, DesiredCapabilities, a hard-coded chromedriver path or webdriver-manager. Each one is either removed from Selenium 4 or a well-known cause of flaky tests.
The Selenium project published its own guidance for AI coding assistants: Selenium’s rules for AI agents. WebdriverIO did the same. Selenium AI Agent turns those rules into a check in code (guardrail 2 from lesson 4): every test the generator writes and every fix the healer applies is checked, and a file with an error is not written.
What you will learn
- Every rule the agent checks, and which are errors and which are warnings
- What a refusal looks like and how the agent recovers from it
- Why mixing implicit and explicit waits is an error
- The extra rule for the healer: no longer timeouts
- When a rule may be overridden, and when not
- How to check an existing suite with
selenium_rules_check, and how to put the rules in your project for every AI tool
The rules
Errors are patterns the Selenium documentation says never to use. A file with an error is refused. Warnings are patterns to avoid where possible. The file is written, and the agent sees the warning.
| Rule | Severity | Catches | Use instead |
|---|---|---|---|
no-sleep | error | time.sleep, Thread.sleep, Task.Delay, driver.sleep, setTimeout promises, Robot Sleep | An explicit wait for the condition the next line needs |
no-implicit-wait | warning, error when mixed | implicitly_wait, implicitlyWait, ImplicitWait =, Robot Set Selenium Implicit Wait | Explicit waits only |
no-driver-manager | error | webdriver_manager, ChromeDriverManager, WebDriverManager, chromedriver_autoinstaller | Selenium Manager (built in since 4.6) |
no-driver-path | error | executable_path=, System.setProperty("webdriver.chrome.driver", ...), a path in Service(...) | Nothing: Selenium Manager finds the driver |
no-desired-capabilities | error | DesiredCapabilities, desired_capabilities= | ChromeOptions, FirefoxOptions, … |
no-selenium3-api | error | find_element_by_*, findElementBy*, switch_to_alert() | find_element(By.ID, ...), switch_to.alert |
old-headless | error | options.headless = True, setHeadless, --headless | --headless=new |
java-timeunit-timeout | error (Java) | implicitlyWait(10, TimeUnit.SECONDS), new WebDriverWait(driver, 10) | Duration.ofSeconds(10) |
csharp-selenium3-api | error (.NET) | new WebDriverWait(driver, 10), ExpectedConditions. | TimeSpan.FromSeconds(10), a lambda condition |
robot-selenium-speed | error (Robot) | Set Selenium Speed | Wait Until ... keywords |
grid3 | error | -role hub / -role node | Grid 4: standalone, hub, node |
no-absolute-xpath | warning | /html/body/div[2]/... | An id, name or data-testid |
no-js-click | warning | execute_script("arguments[0].click()") | Wait until clickable, then click |
no-cdp | warning | execute_cdp_cmd, getDevTools | WebDriver BiDi |
java-browsertype | warning (Java) | BrowserType. | The Browser enum |
csharp-close-not-quit | warning (.NET) | driver.Close(); in teardown | driver.Quit() |
robot-sizzle | warning (Robot) | sizzle: / jquery: locators | css: or id: |
For WebdriverIO the agent uses WebdriverIO’s own rules: no browser.pause() (error), no synchronous mode or v4 APIs (error), no APIs removed in v10 such as executeAsync or switchToFrame (error), no implicit timeouts (warning), and no XPath where a user-facing selector works (warning).
Lines in comments are ignored, so a test may explain why it doesn’t sleep.
Why mixing waits is an error
An implicit wait on its own is only a warning. But as soon as the same file also uses an explicit wait (WebDriverWait, wait.until, Wait Until ...), the warning becomes an error:
ERROR line 8 [no-implicit-wait] driver.implicitly_wait(5)
→ Implicit and explicit waits are mixed. Remove the implicit wait and keep the explicit waits.
The Selenium documentation is explicit: never mix them. An implicit wait makes every find_element inside an explicit wait wait as well, so a 10-second explicit wait with a 5-second implicit wait can take far longer than 10 seconds, and timeouts become unpredictable.
A refusal, and the recovery
You saw this refusal in lesson 4. Real output from generator_write_test:
Test not written: it breaks Selenium's official rules.
Selenium rules (https://www.selenium.dev/documentation/ai_agents/): 2 error(s), 1 warning(s) in guardrail_demo/test_sleep_demo.py
warn line 8 [no-implicit-wait] driver.implicitly_wait(5)
→ Prefer explicit waits. Never mix implicit and explicit waits in the same session.
ERROR line 10 [no-sleep] time.sleep(3)
→ No sleeping in tests. Wait explicitly for the condition the next line depends on (clickable, text present, spinner gone).
ERROR line 11 [no-selenium3-api] driver.find_element_by_css_selector('[data-testid="add-to-cart-2"]').click()
→ Selenium 3 API: removed in Selenium 4. Use find_element(By.ID, ...) / findElement(By.id(...)) / FindElement(By.Id(...)) and switch_to.alert.
Fix these lines and call generator_write_test again.
The refused test:
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_add_to_cart():
driver = webdriver.Chrome()
driver.implicitly_wait(5)
driver.get("https://practiceautomatedtesting.com/shopping")
time.sleep(3)
driver.find_element_by_css_selector('[data-testid="add-to-cart-2"]').click()
assert "1 items" in driver.find_element(By.CSS_SELECTOR, '[data-testid="cart-button"]').text
driver.quit()
Notice that the implicit wait is only a warning here: this file has no explicit wait, so nothing is mixed. Each message names the line, the rule and what to do instead. The agent fixes exactly those lines and saves again:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
def test_add_to_cart():
driver = webdriver.Chrome()
try:
driver.get("https://practiceautomatedtesting.com/shopping")
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[data-testid="add-to-cart-2"]'))).click()
wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, '[data-testid="cart-button"]'), "1 items"))
finally:
driver.quit()
Two improvements came for free: quit() now runs even when the test fails, and the assertion waits for the cart to update. Lesson 3 showed why that matters: the cart button updates after the click returns.
The healer’s extra rule: no longer timeouts
When a test times out, the easiest “fix” is a bigger number: WebDriverWait(driver, 10) becomes WebDriverWait(driver, 30). The healer refuses that. healer_fix_test compares the timeouts in the fix with the highest timeout in the current test, and a higher one is an error:
ERROR line 14 [no-longer-timeout] WebDriverWait(shop.driver, 30).until(...)
→ The timeout goes up from 10s to 30s. A longer timeout hides the race: say which condition
was not true yet, and wait for exactly that.
A longer wait makes a slow page pass, and also makes a broken page take three times as long to fail. The right fix is to wait for the right condition: the spinner gone, the request finished, the text present. This check understands Python, Java Duration, C# TimeSpan, JavaScript and WebdriverIO milliseconds, and Robot Framework timeout= and Set Selenium Timeout.
The refusal text for the healer says the same thing in its own words: find the condition the test waits for instead.
Overriding a rule
Sometimes a team has a reason: a legacy suite that still runs Selenium 3 for a few more months, a third-party widget that only responds to a JavaScript click. generator_write_test and healer_fix_test accept allowRuleViolations: true, and the tool descriptions say when: only when the user explicitly asks for it.
The profile decides whether the override works at all:
| Profile | allowRuleViolations |
|---|---|
explore | allowed |
guided | allowed, and recorded as rule_override_used in the audit log |
strict | ignored: “allowRuleViolations does not apply: the “strict” profile allows no rule overrides.” |
Warnings never need an override; they don’t block anything.
Check a suite you already have
The same rules can check tests nobody generated. selenium_rules_check scans a file or a folder and lists the findings per rule and per file, with line numbers. It changes nothing.
Check the tests in legacy-migration/python with selenium_rules_check.
It is the first thing the migrator agent does (lesson 19), and a cheap way to see how much Selenium 3 is left in an old suite.
The rules in your project, for every AI tool
The agent’s checks only cover what the agent writes. Developers also use Copilot, Cursor or Claude Code directly. init-agents can write the same rules into the instruction file each tool reads:
npx selenium-ai-agent init-agents --loop=claude --with-rules # CLAUDE.md
npx selenium-ai-agent init-agents --loop=cursor --with-rules # .cursor/rules/selenium.mdc
npx selenium-ai-agent init-agents --loop=copilot --with-rules # .github/copilot-instructions.md
The section names the docs index, the pinned Selenium version (read from requirements.txt, pom.xml or package.json), the required patterns and the language’s own notes. It sits between selenium-ai-agent:rules markers, so running the command again replaces only that section and leaves your own instructions alone.
That is an instruction, not a guardrail: an AI can still ignore it. The checks in generator_write_test and healer_fix_test, and the gate in CI (lesson 18), are what enforce it.
Exercise
Without running anything, decide for each snippet: error, warning, or fine? Which rule?
WebDriverWait(driver, 10).until(EC.title_contains("Shop"))options.add_argument("--headless")driver.execute_script("arguments[0].click();", button)- A Java test with
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));and laternew WebDriverWait(driver, Duration.ofSeconds(10)) # time.sleep(2) was here; we now wait for the spinner instead- A heal that changes
WebDriverWait(driver, 10)intoWebDriverWait(driver, 15)
Show suggested answer
- Fine. An explicit wait for a condition.
- Error,
old-headless. Use--headless=new. - Warning,
no-js-click. Wait until the element is clickable and click it natively; a JavaScript click also “clicks” elements a user couldn’t click. - Error,
no-implicit-wait: the file mixes an implicit and an explicit wait. (TheDurationitself is correct;java-timeunit-timeoutwould only catch the oldTimeUnitform.) - Fine. Comments are ignored.
- Error in the healer,
no-longer-timeout: from 10s to 15s. The generator doesn’t check this; it is the healer’s rule, because it compares the fix with the test as it was.
Exam-style questions
1. A test uses driver.implicitly_wait(5) and no explicit waits. What does generator_write_test do?
- A. Refuses it with an error
- B. Writes it with a warning
- C. Removes the implicit wait automatically
- D. Converts it to an explicit wait
Show answer
2. Under the strict profile, the user asks the agent to keep a time.sleep(1) with allowRuleViolations: true. What happens?
- A. The test is written and the override is logged
- B. The test is refused:
strictallows no rule overrides - C. The sleep is replaced by a wait
- D. The profile switches to
guided
Show answer
3. Which statement about init-agents --with-rules is correct?
- A. It enforces the rules for every AI tool in the project
- B. It writes the rules into the instruction file an AI tool reads; the enforcement is in the agent’s tools and the CI gate
- C. It installs a linter in the CI pipeline
- D. It replaces your whole CLAUDE.md