Accessibility Testing with Selenium and axe-core
Automate accessibility checks in Selenium with axe-core in Java, Python, JavaScript and C#, fail builds by impact level, and test keyboard focus order.
Accessibility bugs are product bugs. A checkout button with no accessible name is as broken for a screen reader user as a button that throws a 500 is for everyone else, and in many jurisdictions it is also a legal exposure. The good news: a large class of accessibility defects is mechanical and cheap to catch automatically, and your Selenium suite already visits every important page in every important state. Adding an accessibility scan to those visits is one of the highest-value, lowest-effort things you can do with an existing suite.
This lesson covers the standard tool for the job (axe-core), how to run it from each Selenium binding, how to decide what fails a build, what automation genuinely cannot tell you, and how to test keyboard navigation with plain Selenium.
Why axe-core
axe-core is an open-source JavaScript rules engine from Deque. You inject it into the page, call axe.run(), and it returns a JSON report of rule violations mapped to WCAG success criteria. It is what powers Lighthouse’s accessibility audit, the axe browser extension, and most commercial scanners, so the results your tests produce match what designers and auditors see in their tools.
Three properties make it suitable for CI:
- Low false-positive rate by design. Rules that cannot be decided with certainty are reported as
incomplete(“needs review”) rather than as violations. Failing a build onviolationsdoes not produce a stream of noise. - Runs against the live DOM. It sees the page after JavaScript has rendered it, with whatever state your test put it in: an open modal, a validation error, an expanded menu.
- Every binding has a wrapper, so you do not need to manage the script injection yourself.
| Language | Package | Notes |
|---|---|---|
| Java | com.deque.html.axe-core:selenium (Maven) | Official Deque wrapper; bundles axe-core |
| JavaScript | @axe-core/webdriverjs (npm) | Official Deque wrapper for selenium-webdriver |
| C# | Deque.AxeCore.Selenium (NuGet) | Official Deque wrapper; replaces the older community Selenium.Axe package |
| Python | No official open-source Deque wrapper; inject axe.min.js yourself | The community axe-selenium-python package works but bundles an old axe-core and is not actively maintained |
Running a Scan
The shape is the same everywhere: navigate, get the page into the state you want to check, run axe, inspect violations.
// pom.xml: com.deque.html.axe-core:selenium (current 4.x)import com.deque.html.axecore.selenium.AxeBuilder;import com.deque.html.axecore.results.Results;import com.deque.html.axecore.results.Rule;
driver.get("https://app.example.com/checkout");new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.visibilityOfElementLocated(By.id("payment-form")));
Results results = new AxeBuilder() .withTags(List.of("wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa")) .analyze(driver);
for (Rule rule : results.getViolations()) { System.out.printf("[%s] %s (%d nodes) %s%n", rule.getImpact(), rule.getId(), rule.getNodes().size(), rule.getHelpUrl());}
assertTrue(results.violationFree(), "Accessibility violations found");# Download axe.min.js once (npm i axe-core, or pin a copy in your repo)from pathlib import Path
AXE_SOURCE = Path("vendor/axe.min.js").read_text(encoding="utf-8")
def run_axe(driver, options=None): driver.execute_script(AXE_SOURCE) # execute_async_script passes a callback as the last argument return driver.execute_async_script( """ const done = arguments[arguments.length - 1]; axe.run(document, arguments[0]) .then(results => done(results)) .catch(err => done({ error: err.toString() })); """, options or {"runOnly": {"type": "tag", "values": ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]}}, )
driver.get("https://app.example.com/checkout")WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "payment-form")))driver.set_script_timeout(30) # big pages can take several seconds to scan
results = run_axe(driver)assert "error" not in results, results.get("error")
for v in results["violations"]: print(f"[{v['impact']}] {v['id']} ({len(v['nodes'])} nodes) {v['helpUrl']}")
assert not results["violations"], "Accessibility violations found"// npm i @axe-core/webdriverjsconst AxeBuilder = require('@axe-core/webdriverjs');
await driver.get('https://app.example.com/checkout');await driver.wait(until.elementLocated(By.id('payment-form')), 10000);
const results = await new AxeBuilder(driver).withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']).analyze();
for (const v of results.violations) {console.log(`[${v.impact}] ${v.id} (${v.nodes.length} nodes) ${v.helpUrl}`);}
assert.strictEqual(results.violations.length, 0, 'Accessibility violations found');// dotnet add package Deque.AxeCore.Seleniumusing Deque.AxeCore.Commons;using Deque.AxeCore.Selenium;
driver.Navigate().GoToUrl("https://app.example.com/checkout");new WebDriverWait(driver, TimeSpan.FromSeconds(10)) .Until(d => d.FindElement(By.Id("payment-form")).Displayed);
AxeResult results = new AxeBuilder(driver) .WithTags("wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa") .Analyze();
foreach (var v in results.Violations){ Console.WriteLine($"[{v.Impact}] {v.Id} ({v.Nodes.Length} nodes) {v.HelpUrl}");}
Assert.That(results.Violations, Is.Empty, "Accessibility violations found");A few practical details:
- Tags select the standard.
wcag2aandwcag2aaare WCAG 2.0;wcag21aaandwcag22aaadd the newer criteria. Most organisations target WCAG 2.1 or 2.2 AA. Without tags axe also runsbest-practicerules, which are useful advice but not conformance requirements; decide deliberately whether they can fail your build. - Wait for the state you care about first. Scanning a page mid-render reports the skeleton loader, not your UI. Use the same explicit waits you would use before an assertion; see Explicit Waits.
- The Python injection approach works in every binding. If a wrapper ever lags behind axe-core releases, or you need a specific axe version, injecting
axe.min.jswith an async script is the escape hatch. See JavaScript Executor for how async scripts and callbacks work.
Scoping: Include, Exclude and Disable
Real pages contain things you do not own: a third-party chat widget, an embedded map, an ad slot. Scope the scan so the build fails on your defects, and track the third-party ones separately.
Results results = new AxeBuilder() .withTags(List.of("wcag2a", "wcag2aa", "wcag21aa")) .exclude("#intercom-container") // third-party widget .exclude("iframe[src*='maps.google']") .disableRules(List.of("color-contrast")) // JIRA-1234: brand palette fix in progress .analyze(driver);
// Or scan only one componentResults modal = new AxeBuilder().include("#login-modal").analyze(driver);# axe.min.js already injected by run_axe() or driver.execute_script(AXE_SOURCE)
results = driver.execute_async_script(""" const done = arguments[arguments.length - 1]; axe.run( { exclude: [['#intercom-container'], ["iframe[src*='maps.google']"]] }, { runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21aa'] }, rules: { 'color-contrast': { enabled: false } } } // JIRA-1234 ).then(done).catch(e => done({ error: e.toString() }));""")
# Scan only one componentmodal = driver.execute_async_script(""" const done = arguments[arguments.length - 1]; axe.run('#login-modal').then(done).catch(e => done({ error: e.toString() }));""")const results = await new AxeBuilder(driver).withTags(['wcag2a', 'wcag2aa', 'wcag21aa']).exclude('#intercom-container').exclude("iframe[src*='maps.google']").disableRules(['color-contrast']) // JIRA-1234.analyze();
// Or scan only one componentconst modal = await new AxeBuilder(driver).include('#login-modal').analyze();AxeResult results = new AxeBuilder(driver) .WithTags("wcag2a", "wcag2aa", "wcag21aa") .Exclude("#intercom-container") .Exclude("iframe[src*='maps.google']") .DisableRules("color-contrast") // JIRA-1234 .Analyze();
// Or scan only one componentAxeResult modal = new AxeBuilder(driver).Include("#login-modal").Analyze();Every disabled rule should carry a ticket reference in a comment. A disableRules list with no owner is how a codebase drifts from “one known contrast issue” to “contrast checks have been off for two years”.
Failing the Build by Impact
Each violation carries an impact of minor, moderate, serious or critical. A sensible rollout on an existing product, where the first scan typically finds dozens of issues:
- Week one: report everything, fail on nothing. Publish the JSON or HTML report as a CI artifact.
- Then: fail on
criticalandserious. These are the defects that block users outright: missing form labels, buttons with no name, keyboard traps, images of text with no alternative. - Ratchet down to
moderateonce the backlog is cleared, and keep it there so regressions are caught the day they are introduced.
private static final Set<String> BLOCKING = Set.of("critical", "serious");
static void assertNoBlockingViolations(Results results) { List<Rule> blocking = results.getViolations().stream() .filter(r -> BLOCKING.contains(r.getImpact())) .toList();
if (!blocking.isEmpty()) { String report = blocking.stream() .map(r -> String.format("%s [%s]: %s%n %s%n first target: %s", r.getId(), r.getImpact(), r.getHelp(), r.getHelpUrl(), r.getNodes().get(0).getTarget())) .collect(Collectors.joining("\n")); fail(blocking.size() + " blocking accessibility violation(s):\n" + report); }}BLOCKING = {"critical", "serious"}
def assert_no_blocking_violations(results): blocking = [v for v in results["violations"] if v["impact"] in BLOCKING] if blocking: lines = [ f"{v['id']} [{v['impact']}]: {v['help']}\n {v['helpUrl']}\n" f" first target: {v['nodes'][0]['target']}" for v in blocking ] raise AssertionError( f"{len(blocking)} blocking accessibility violation(s):\n" + "\n".join(lines))const BLOCKING = new Set(['critical', 'serious']);
function assertNoBlockingViolations(results) {const blocking = results.violations.filter((v) => BLOCKING.has(v.impact));if (blocking.length) { const report = blocking .map((v) => `${v.id} [${v.impact}]: ${v.help}\n ${v.helpUrl}\n first target: ${v.nodes[0].target}`) .join('\n'); throw new Error(`${blocking.length} blocking accessibility violation(s):\n${report}`);}}private static readonly HashSet<string> Blocking = new() { "critical", "serious" };
static void AssertNoBlockingViolations(AxeResult results){ var blocking = results.Violations.Where(v => Blocking.Contains(v.Impact)).ToList(); if (blocking.Count == 0) return;
var report = string.Join("\n", blocking.Select(v => $"{v.Id} [{v.Impact}]: {v.Help}\n {v.HelpUrl}\n first target: {v.Nodes[0].Target}")); Assert.Fail($"{blocking.Count} blocking accessibility violation(s):\n{report}");}The failure message matters. “Accessibility violations found” sends a developer to dig through JSON; “button-name [critical]: Buttons must have discernible text, first target: #cart > button.icon” sends them straight to the fix.
Where to scan
Do not scan after every click; a full scan takes from a few hundred milliseconds to several seconds on a heavy page. Scan at meaningful states:
- Each distinct page template once it has loaded.
- Each modal, drawer and menu when open.
- Each form after a failed submit, when error messages are shown (error messages are a frequent source of missing
aria-describedbyand contrast failures). - Logged-in and logged-out variants of the shell.
A clean way to do this is a scanAccessibility(String stateName) helper in your base page object that runs axe, attaches the report to the test result, and applies the impact policy. Pair it with Reporting with Allure and Extent so the report travels with the build.
What Automation Catches and What It Misses
Automated scanners find roughly a third to a half of WCAG issues by volume, depending on whose study you read. That is a lot of issues for no human effort, but it is not conformance, and a clean axe report is not an accessibility sign-off.
| Automated checks catch reliably | Automated checks cannot judge |
|---|---|
Images without an alt attribute | Whether the alt text is meaningful (“image123.png” passes) |
| Form inputs with no programmatic label | Whether the label describes the field correctly |
| Insufficient colour contrast on text with a solid background | Contrast of text over images and gradients (reported as “needs review”) |
| Invalid or misused ARIA attributes and roles | Whether the ARIA pattern behaves correctly with a real screen reader |
| Missing document language, page title, duplicate IDs | Whether headings describe the content and reading order makes sense |
| Buttons and links with no accessible name | Whether focus moves sensibly when a modal opens or closes |
| Missing landmark structure (best-practice rules) | Keyboard traps in custom widgets, timing issues, captions on video |
The right side of that table needs two things: targeted Selenium tests for behaviour you can assert (keyboard navigation and focus management, below), and periodic manual testing with real assistive technology (NVDA, JAWS, VoiceOver, TalkBack) by someone who uses them well.
Note: Treat axe’s
incompleteresults as a work queue for manual review, not as failures. Log their count per page so you can see when it changes.
Testing Keyboard Navigation
Keyboard operability is the foundation many other assistive technologies build on, and it is something Selenium can test directly. The core tool is switchTo().activeElement(), which returns whichever element currently has focus.
Tab order
driver.get("https://app.example.com/login");driver.findElement(By.tagName("body")).click(); // start from a known point
List<String> expectedOrder = List.of("email", "password", "remember-me", "sign-in");Actions actions = new Actions(driver);
for (String expectedId : expectedOrder) { actions.sendKeys(Keys.TAB).perform(); WebElement focused = driver.switchTo().activeElement(); assertEquals(expectedId, focused.getAttribute("id"), "Unexpected focus after TAB; focused: " + focused.getAttribute("outerHTML"));}from selenium.webdriver.common.action_chains import ActionChainsfrom selenium.webdriver.common.keys import Keys
driver.get("https://app.example.com/login")driver.find_element(By.TAG_NAME, "body").click()
expected_order = ["email", "password", "remember-me", "sign-in"]actions = ActionChains(driver)
for expected_id in expected_order: actions.send_keys(Keys.TAB).perform() focused = driver.switch_to.active_element assert focused.get_attribute("id") == expected_id, ( f"Unexpected focus after TAB: {focused.get_attribute('outerHTML')}")await driver.get('https://app.example.com/login');await driver.findElement(By.css('body')).click();
const expectedOrder = ['email', 'password', 'remember-me', 'sign-in'];
for (const expectedId of expectedOrder) {await driver.actions().sendKeys(Key.TAB).perform();const focused = await driver.switchTo().activeElement();assert.strictEqual(await focused.getAttribute('id'), expectedId, `Unexpected focus after TAB: ${await focused.getAttribute('outerHTML')}`);}driver.Navigate().GoToUrl("https://app.example.com/login");driver.FindElement(By.TagName("body")).Click();
var expectedOrder = new[] { "email", "password", "remember-me", "sign-in" };var actions = new Actions(driver);
foreach (var expectedId in expectedOrder){ actions.SendKeys(Keys.Tab).Perform(); var focused = driver.SwitchTo().ActiveElement(); Assert.That(focused.GetAttribute("id"), Is.EqualTo(expectedId), $"Unexpected focus after TAB: {focused.GetAttribute("outerHTML")}");}Send TAB through the Actions API rather than element.sendKeys(Keys.TAB) on a specific element: you want to press the key wherever focus actually is, which is exactly what you are testing. For more on key handling, see Keyboard Actions.
Visible focus and operability
Two more checks are cheap and catch common regressions:
- Focus is visible. WCAG 2.4.7 requires a visible focus indicator. A CSS reset with
outline: noneand no replacement is a classic regression. After tabbing to an element, compare its computedoutline-style,outline-widthorbox-shadowagainst the unfocused state usinggetCssValue. This is a heuristic (designers can indicate focus in other ways), so fail only when nothing changes. - Controls work from the keyboard. Tab to a custom dropdown and press ENTER or SPACE, then assert it opened; press ESCAPE and assert it closed and focus returned to the trigger.
WebElement trigger = driver.findElement(By.id("open-settings"));trigger.sendKeys(Keys.ENTER);
WebElement dialog = new WebDriverWait(driver, Duration.ofSeconds(5)) .until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[role='dialog']")));
// 1. Focus moved inside the dialogassertTrue((Boolean) ((JavascriptExecutor) driver).executeScript( "return arguments[0].contains(document.activeElement);", dialog));
// 2. Focus is trapped: 20 TABs never leave the dialogActions actions = new Actions(driver);for (int i = 0; i < 20; i++) { actions.sendKeys(Keys.TAB).perform(); assertTrue((Boolean) ((JavascriptExecutor) driver).executeScript( "return arguments[0].contains(document.activeElement);", dialog), "Focus escaped dialog");}
// 3. ESC closes and focus returns to the triggeractions.sendKeys(Keys.ESCAPE).perform();new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.invisibilityOf(dialog));assertEquals(trigger, driver.switchTo().activeElement());trigger = driver.find_element(By.ID, "open-settings")trigger.send_keys(Keys.ENTER)
dialog = WebDriverWait(driver, 5).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "[role='dialog']")))
contains_focus = "return arguments[0].contains(document.activeElement);"assert driver.execute_script(contains_focus, dialog)
actions = ActionChains(driver)for _ in range(20): actions.send_keys(Keys.TAB).perform() assert driver.execute_script(contains_focus, dialog), "Focus escaped dialog"
actions.send_keys(Keys.ESCAPE).perform()WebDriverWait(driver, 5).until(EC.invisibility_of_element(dialog))assert driver.switch_to.active_element == triggerconst trigger = await driver.findElement(By.id('open-settings'));await trigger.sendKeys(Key.ENTER);
const dialog = await driver.wait(until.elementLocated(By.css("[role='dialog']")), 5000);await driver.wait(until.elementIsVisible(dialog), 5000);
const containsFocus = 'return arguments[0].contains(document.activeElement);';assert.ok(await driver.executeScript(containsFocus, dialog));
for (let i = 0; i < 20; i++) {await driver.actions().sendKeys(Key.TAB).perform();assert.ok(await driver.executeScript(containsFocus, dialog), 'Focus escaped dialog');}
await driver.actions().sendKeys(Key.ESCAPE).perform();await driver.wait(until.elementIsNotVisible(dialog), 5000);const active = await driver.switchTo().activeElement();assert.strictEqual(await active.getId(), await trigger.getId());var trigger = driver.FindElement(By.Id("open-settings"));trigger.SendKeys(Keys.Enter);
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));var dialog = wait.Until(d => d.FindElements(By.CssSelector("[role='dialog']")).FirstOrDefault(e => e.Displayed));
const string containsFocus = "return arguments[0].contains(document.activeElement);";var js = (IJavaScriptExecutor)driver;Assert.That((bool)js.ExecuteScript(containsFocus, dialog), Is.True);
var actions = new Actions(driver);for (int i = 0; i < 20; i++){ actions.SendKeys(Keys.Tab).Perform(); Assert.That((bool)js.ExecuteScript(containsFocus, dialog), Is.True, "Focus escaped dialog");}
actions.SendKeys(Keys.Escape).Perform();wait.Until(_ => !dialog.Displayed);Assert.That(driver.SwitchTo().ActiveElement(), Is.EqualTo(trigger));Warning: Keyboard tests are sensitive to headless window size and to whether the browser window has OS focus. If tab order tests pass locally and fail in CI, set an explicit window size and avoid running multiple headed browsers on one desktop session. See Headless Browsers.
Putting It in CI
- Pin the axe-core version (through the wrapper version or your vendored
axe.min.js). New axe releases add rules; an upgrade should be a deliberate change with its own pull request, not a surprise red build. - Save the full JSON per scanned state as a build artifact. Deque’s
axe-html-reporter(npm) or the wrappers’ report helpers turn it into HTML for non-engineers. - Run scans in one browser. Results are nearly identical across Chrome and Firefox; scanning in every browser in your matrix multiplies time for little gain.
- Keep the suite deterministic. Scans on pages with rotating banners or A/B tests produce varying results. Pin experiments with cookies or feature flags the same way you would for visual regression testing.
Summary
- axe-core is the standard engine; use
com.deque.html.axe-core:selenium(Java),@axe-core/webdriverjs(JS),Deque.AxeCore.Selenium(C#), and injectaxe.min.jsfrom Python. - Scan at meaningful UI states, scope out third-party regions, and give every disabled rule an owner.
- Fail builds on
criticalandseriousfirst, then ratchet down. - Automation catches the mechanical half of WCAG. Add Selenium keyboard and focus tests for behaviour, and manual assistive-technology testing for the rest.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.