DEV Community

appierun
appierun

Posted on

Audit Accessibility Basics Across Your Sitemap with Python (Stdlib Only): Missing lang, Zoom-Blocking and Unlabelled Fields

A full accessibility review needs a person, a keyboard and a screen reader. But a lot of the problems on small business sites are mechanical and repeat on every page: a phone icon link with no text, a theme that turns off pinch zoom, a newsletter box with a placeholder instead of a label, a template that forgot the lang attribute. Those you can find with a script.

If you look after sites for a few local clients, this post builds a small Python script (standard library only) that reads a sitemap, fetches each page and flags those basics. It does not replace a manual review or a browser-based checker. It tells you where to look first, on every page, in under a minute.

Disclosure: Appie.run publishes this post. The only Appie mentions are two free sitemap tools near the end. Everything else is plain Python you can run yourself. The test site is a fictional local plumber built for this post and served from localhost. The WCAG wording below is from the W3C's WCAG 2.2 Understanding documents for success criteria 3.1.1, 1.4.4, 2.4.4, 4.1.2 and 3.3.2, and the viewport note is from MDN. I read all six pages on 28 Nov 2026.

What WCAG and MDN say

Each check maps to a WCAG 2.2 success criterion. The quotes are from the W3C Understanding pages:

  • 3.1.1 Language of Page: "The default human language of each web page can be programmatically determined." On HTML pages that means a lang attribute on <html>, such as lang="en".
  • 1.4.4 Resize Text: text "can be resized without assistive technology up to 200 percent without loss of content or functionality."
  • 2.4.4 Link Purpose (In Context): "The purpose of each link can be determined from the link text alone or from the link text together with its programmatically determined link context."
  • 4.1.2 Name, Role, Value: "For all user interface components (including but not limited to: form elements, links and components generated by scripts), the name and role can be programmatically determined."
  • 3.3.2 Labels or Instructions: "Labels or instructions are provided when content requires user input."

And MDN's viewport meta page warns: "Disabling zooming capabilities by setting user-scalable to a value of no prevents people experiencing low vision conditions from being able to read and understand page content." It also notes that browser settings can ignore these rules and that iOS 10+ ignores them by default, so the viewport check is about intent and other browsers, not every device.

What the audit checks

Check Severity What it means
lang-missing error <html> has no lang attribute
lang-invalid error lang is not shaped like a language tag (english instead of en)
viewport-zoom error viewport has user-scalable=no or maximum-scale below 2
link-no-name error a link has no text, no image alt text and no aria-label (icon links)
link-vague review link text is only "click here", "read more" and similar
button-no-name error a button has no text and no aria-label (icon buttons)
field-no-label error an input, select or textarea has no <label>, no wrapping label and no aria-label / aria-labelledby / title; placeholder-only fields are called out
label-for-missing-id error <label for="x"> points at an id that does not exist
duplicate-id error the same id appears more than once on a page (this breaks label for)
positive-tabindex review tabindex greater than 0 changes the keyboard order

What it does not check: colour contrast, focus visibility, keyboard traps, heading order, image alt text quality, ARIA correctness in depth, or anything built by JavaScript after load. It reads the HTML the server sends. Hidden inputs and submit, reset, button and image inputs are skipped for the label check because they do not need a visible label.

The script

Save as a11y_audit.py. It needs Python 3.9+ and nothing outside the standard library.

#!/usr/bin/env python3
"""Accessibility basics audit across a sitemap (standard library only).

Checks each page for: missing or malformed lang on <html>, a viewport that blocks zoom,
links and buttons with no accessible name, vague link text, form fields without a label,
labels that point at a missing id, duplicate ids and positive tabindex.

Usage: python3 a11y_audit.py https://example.com/sitemap.xml [--csv report.csv]
Exit code 1 if any "error" finding, else 0.
"""
import csv, re, sys, time, urllib.request
import xml.etree.ElementTree as ET
from html.parser import HTMLParser

UA = "a11y-basics-audit/1.0 (+contact: you@example.com)"
SM_NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
LANG_RE = re.compile(r"^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$")  # rough BCP 47 shape check
VAGUE = {"click here", "here", "read more", "more", "learn more", "this page", "link"}
UNLABELLED_OK = {"hidden", "submit", "button", "reset", "image"}

def fetch(url):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=20) as r:
        return r.read().decode(r.headers.get_content_charset() or "utf-8", "replace")

def sitemap_urls(url):
    root = ET.fromstring(fetch(url))
    if root.tag == SM_NS + "sitemapindex":
        out = []
        for loc in root.iter(SM_NS + "loc"):
            out += sitemap_urls(loc.text.strip())
        return out
    return [loc.text.strip() for loc in root.iter(SM_NS + "loc")]

class Page(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.html_lang = None; self.saw_html = False
        self.viewport = None
        self.ids = {}                 # id -> count
        self.label_for = []           # ids referenced by <label for>
        self.controls = []            # dicts: tag, type, id, name, aria, placeholder, wrapped
        self.links, self.buttons = [], []
        self.pos_tabindex = []
        self._label_depth = 0
        self._stack = []              # open <a>/<button> collectors

    def handle_starttag(self, tag, attrs):
        a = {k: (v or "") for k, v in attrs}
        if tag == "html":
            self.saw_html = True; self.html_lang = a.get("lang")
        if tag == "meta" and a.get("name", "").lower() == "viewport":
            self.viewport = a.get("content", "")
        if "id" in a:
            self.ids[a["id"]] = self.ids.get(a["id"], 0) + 1
        ti = a.get("tabindex", "").strip()
        if ti.lstrip("-").isdigit() and int(ti) > 0:
            self.pos_tabindex.append(f"<{tag}> tabindex={ti}")
        if tag == "label":
            self._label_depth += 1
            if a.get("for"): self.label_for.append(a["for"])
        if tag in ("input", "select", "textarea"):
            self.controls.append({"tag": tag, "type": a.get("type", "text").lower() if tag == "input" else tag,
                "id": a.get("id", ""), "name": a.get("name", ""),
                "aria": bool(a.get("aria-label", "").strip() or a.get("aria-labelledby", "").strip() or a.get("title", "").strip()),
                "placeholder": a.get("placeholder", ""), "wrapped": self._label_depth > 0})
        if tag in ("a", "button") and (tag == "button" or "href" in a):
            self._stack.append({"tag": tag, "href": a.get("href", ""), "text": "",
                "aria": a.get("aria-label", "").strip() or a.get("aria-labelledby", "").strip(),
                "title": a.get("title", "").strip(), "alt": ""})
        if tag == "img" and self._stack:
            self._stack[-1]["alt"] += " " + a.get("alt", "")

    def handle_endtag(self, tag):
        if tag == "label" and self._label_depth: self._label_depth -= 1
        if tag in ("a", "button") and self._stack and self._stack[-1]["tag"] == tag:
            item = self._stack.pop()
            (self.links if tag == "a" else self.buttons).append(item)

    def handle_data(self, data):
        if self._stack: self._stack[-1]["text"] += data

def viewport_problem(content):
    if content is None: return None
    parts = {}
    for p in content.split(","):
        if "=" in p:
            k, v = p.split("=", 1); parts[k.strip().lower()] = v.strip().lower()
    if parts.get("user-scalable") in ("no", "0"): return "user-scalable=no blocks zoom"
    try:
        if "maximum-scale" in parts and float(parts["maximum-scale"]) < 2:
            return f"maximum-scale={parts['maximum-scale']} limits zoom below 200%"
    except ValueError:
        pass
    return None

def audit(url, html):
    p = Page(); p.feed(html); f = []
    add = lambda sev, check, detail: f.append((url, sev, check, detail))
    if not p.html_lang or not p.html_lang.strip():
        add("error", "lang-missing", "<html> has no lang attribute")
    elif not LANG_RE.match(p.html_lang.strip()):
        add("error", "lang-invalid", f'lang="{p.html_lang}" is not a language tag like "en" or "en-GB"')
    vp = viewport_problem(p.viewport)
    if vp: add("error", "viewport-zoom", vp)
    for l in p.links:
        name = " ".join((l["text"] + " " + l["alt"]).split()) or l["aria"]
        if not name:
            add("error", "link-no-name", f'<a href="{l["href"]}"> has no text, alt or aria-label' + (" (title only)" if l["title"] else ""))
        elif name.lower().strip(" .") in VAGUE:
            add("review", "link-vague", f'<a href="{l["href"]}"> text "{name}"')
    for b in p.buttons:
        if not (" ".join((b["text"] + " " + b["alt"]).split()) or b["aria"]):
            add("error", "button-no-name", "<button> has no text or aria-label")
    labelled = set(p.label_for)
    for c in p.controls:
        if c["type"] in UNLABELLED_OK: continue
        if c["wrapped"] or c["aria"] or (c["id"] and c["id"] in labelled): continue
        extra = f' (placeholder "{c["placeholder"]}" only)' if c["placeholder"] else ""
        add("error", "field-no-label", f'<{c["tag"]} name="{c["name"]}">{extra}')
    for ref in p.label_for:
        if ref not in p.ids:
            add("error", "label-for-missing-id", f'<label for="{ref}"> points at no element')
    for i, n in p.ids.items():
        if n > 1: add("error", "duplicate-id", f'id="{i}" used {n} times')
    for t in p.pos_tabindex:
        add("review", "positive-tabindex", t)
    return f

def main():
    if len(sys.argv) < 2:
        sys.exit(__doc__)
    sm = sys.argv[1]
    csv_path = sys.argv[sys.argv.index("--csv") + 1] if "--csv" in sys.argv else None
    urls = sitemap_urls(sm)
    print(f"Sitemap: {sm}\nPages: {len(urls)}\n")
    findings = []
    for u in urls:
        try:
            findings += audit(u, fetch(u))
        except Exception as e:
            findings.append((u, "error", "fetch-failed", str(e)))
        time.sleep(0.5)
    for u in urls:
        rows = [x for x in findings if x[0] == u]
        print(f"{u}  {'OK' if not rows else str(len(rows)) + ' finding(s)'}")
        for _, sev, check, detail in rows:
            print(f"  [{sev}] {check}: {detail}")
    errors = sum(1 for x in findings if x[1] == "error")
    reviews = len(findings) - errors
    print(f"\nSummary: {errors} error(s), {reviews} to review, {len(urls)} page(s)")
    if csv_path:
        with open(csv_path, "w", newline="") as fh:
            w = csv.writer(fh); w.writerow(["url", "severity", "check", "detail"]); w.writerows(findings)
        print(f"CSV written: {csv_path}")
    sys.exit(1 if errors else 0)

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

A few design notes:

  • Accessible name is approximated. For links and buttons, the script counts visible text, alt text of images inside, aria-label and aria-labelledby. A title alone is reported as "(title only)" and still flagged, because support for title as a name is unreliable. A browser computes names with more rules than this; treat a pass as "probably fine," not proof.
  • The language check is a shape check. It accepts en, en-GB, pt-BR and rejects english or an empty value. It does not check that the language is correct for the content.
  • It is polite. A 0.5 second pause between pages and a User-Agent with a contact address. Change the address before running it on a client site.

The test site

The fixture is a fictional plumber, "Northgate Plumbing," with five pages: home, services, areas, a blog post with a newsletter form, and a contact form. A small server (serve_fixture.py) serves it on localhost:8498 in two modes, before and after. In before mode it has:

  • A phone icon link in the header and a Facebook icon link in the footer (image with empty alt) on every page, neither with a name
  • A viewport with maximum-scale=1, user-scalable=no on the home page
  • An icon-only menu button on the home page
  • No lang on the services page and lang="english" on the areas page
  • "Click here" and "Read more" link text
  • A newsletter email field with only a placeholder
  • On the contact form: a label pointing at phone-number while the input's id is phone, a postcode field that reuses id="name" and has only a placeholder, a <select> with no label, and a submit button with tabindex="3"

The relevant bits of the before HTML look like this:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<a href="tel:+15550100"><svg width="16" height="16" aria-hidden="true">...</svg></a>
<a href="/facebook"><img src="/static/fb.png" alt=""></a>
<button type="button" class="menu-toggle"><svg ...></svg></button>

<label for="phone-number">Phone</label><input type="tel" id="phone" name="phone">
<input type="text" id="name" name="postcode" placeholder="Postcode">
<select name="urgency"><option>Today</option><option>This week</option></select>
<button type="submit" tabindex="3">Request a visit</button>
Enter fullscreen mode Exit fullscreen mode

Running it: before

python3 serve_fixture.py before &
python3 a11y_audit.py http://localhost:8498/sitemap.xml --csv a11y_report_before.csv
Enter fullscreen mode Exit fullscreen mode

This is the real output from the fixture:

Sitemap: http://localhost:8498/sitemap.xml
Pages: 5

http://localhost:8498/  5 finding(s)
  [error] viewport-zoom: user-scalable=no blocks zoom
  [error] link-no-name: <a href="tel:+15550100"> has no text, alt or aria-label
  [review] link-vague: <a href="/contact"> text "Click here"
  [error] link-no-name: <a href="/facebook"> has no text, alt or aria-label
  [error] button-no-name: <button> has no text or aria-label
http://localhost:8498/services  4 finding(s)
  [error] lang-missing: <html> has no lang attribute
  [error] link-no-name: <a href="tel:+15550100"> has no text, alt or aria-label
  [review] link-vague: <a href="/services/boilers"> text "Read more"
  [error] link-no-name: <a href="/facebook"> has no text, alt or aria-label
http://localhost:8498/areas  3 finding(s)
  [error] lang-invalid: lang="english" is not a language tag like "en" or "en-GB"
  [error] link-no-name: <a href="tel:+15550100"> has no text, alt or aria-label
  [error] link-no-name: <a href="/facebook"> has no text, alt or aria-label
http://localhost:8498/blog/frozen-pipes  3 finding(s)
  [error] link-no-name: <a href="tel:+15550100"> has no text, alt or aria-label
  [error] link-no-name: <a href="/facebook"> has no text, alt or aria-label
  [error] field-no-label: <input name="email"> (placeholder "Your email" only)
http://localhost:8498/contact  7 finding(s)
  [error] link-no-name: <a href="tel:+15550100"> has no text, alt or aria-label
  [error] link-no-name: <a href="/facebook"> has no text, alt or aria-label
  [error] field-no-label: <input name="phone">
  [error] field-no-label: <select name="urgency">
  [error] label-for-missing-id: <label for="phone-number"> points at no element
  [error] duplicate-id: id="name" used 2 times
  [review] positive-tabindex: <button> tabindex=3

Summary: 19 error(s), 3 to review, 5 page(s)
CSV written: a11y_report_before.csv
$ echo $?
1
Enter fullscreen mode Exit fullscreen mode

Reading it:

  • The header and footer icons account for 10 of the 19 errors. Two template fixes clear every page. This is typical: on small sites most accessibility errors live in the theme, not the content.
  • The postcode field is not in the list, and that is the point of the duplicate-id check. The label for="name" exists, and the postcode input has id="name", so a naive "is there a label for this id" check passes it. The duplicate-id finding is what tells you something is wrong: the "Name" label belongs to the first field, and the postcode box has only a placeholder.
  • The phone field has a label, but it points at the wrong id. label-for-missing-id and field-no-label on the same page are usually one bug.
  • link-vague and positive-tabindex are review items. "Read more" may be fine when the surrounding sentence makes the purpose clear (WCAG 2.4.4 allows link context). A positive tabindex is almost always a mistake, but check before you remove it.

Fixing it

The fixes in after mode:

<meta name="viewport" content="width=device-width, initial-scale=1">
<a href="tel:+15550100" aria-label="Call Northgate Plumbing"><svg ... aria-hidden="true"></svg></a>
<a href="/facebook" aria-label="Northgate Plumbing on Facebook"><img src="/static/fb.png" alt="Facebook"></a>
<button type="button" class="menu-toggle" aria-label="Open menu"><svg ...></svg></button>
<html lang="en">

<a href="/contact">Book an emergency visit</a>
<a href="/services/boilers">Boiler servicing prices</a>

<label for="email-news">Email</label><input type="email" id="email-news" name="email">
<label for="phone">Phone</label><input type="tel" id="phone" name="phone">
<label for="postcode">Postcode</label><input type="text" id="postcode" name="postcode">
<select name="urgency" aria-label="How urgent is it?">...</select>
<button type="submit">Request a visit</button>
Enter fullscreen mode Exit fullscreen mode

A visible <label> is better than aria-label for form fields because sighted users see it too. I used aria-label on the select only to show that the check accepts it.

Running it: after

python3 serve_fixture.py after &
python3 a11y_audit.py http://localhost:8498/sitemap.xml --csv a11y_report_after.csv
Enter fullscreen mode Exit fullscreen mode
Sitemap: http://localhost:8498/sitemap.xml
Pages: 5

http://localhost:8498/  OK
http://localhost:8498/services  OK
http://localhost:8498/areas  OK
http://localhost:8498/blog/frozen-pipes  OK
http://localhost:8498/contact  OK

Summary: 0 error(s), 0 to review, 5 page(s)
CSV written: a11y_report_after.csv
$ echo $?
0
Enter fullscreen mode Exit fullscreen mode

Exit code 0, so you can drop it into a scheduled job or CI step and fail the build when an error appears.

Running it on a client site

  • Ask first and run it slowly. It is one request per page with a pause, but it is still the client's server.
  • Start with the template. Sort the CSV by check and detail. Anything that repeats on every URL is in the header, footer or a shared component; fix it once.
  • Check page builders and plugins. Newsletter, booking and chat widgets are common sources of unlabelled fields and icon buttons. If they render with JavaScript, this script will not see them; use a browser-based checker for those.
  • Check text files in the sitemap. If a sitemap lists non-HTML files (a .txt or .pdf), the script will report lang-missing for them. Filter those out or skip URLs whose Content-Type is not HTML.
  • Pair it with a manual pass. Tab through the contact form, zoom to 200%, and try the menu with a keyboard. Ten minutes per client catches what no parser will.

Related free tools

If you need the URL list without writing code, our free Sitemap URL Extractor returns one URL per line from a sitemap URL or pasted sitemap XML (for a sitemap index it lists the child sitemaps, which you then open one at a time). The Sitemap Finder and Checker finds sitemaps on a site and counts their URLs. Neither runs accessibility checks; they only get you the list.

FAQ

Does passing this script mean a site is accessible?
No. It checks a handful of mechanical issues in server-sent HTML. Contrast, focus, keyboard use, headings, media and JavaScript-built content all need other tools and a person.

Is user-scalable=no still a problem if iOS ignores it?
MDN notes that iOS 10+ ignores it by default, but other browsers and settings may not. It also signals that the page was designed not to be zoomed. Remove it.

Is aria-label enough for an icon link?
It gives the link a name assistive technology can read. Visible text is better when the design allows it, and the icon itself should be hidden from assistive technology with aria-hidden="true" as in the fixture.

Why flag "read more" as review instead of error?
WCAG 2.4.4 allows the purpose to come from the link text together with its context, such as the sentence or list item around it. The script cannot judge that, so it asks you to.

Can I run this in CI?
Yes. It exits 1 when there is any error-level finding and 0 otherwise, and --csv writes a file you can keep as a build artifact.


RG, Founder, Appie.run

Top comments (0)