Headings do two jobs. People skim them, and screen reader users jump between them to understand a page. A template change can quietly break that across hundreds of pages: a promo banner styled as an <h3> lands above the title, a section jumps from <h2> straight to <h4> because the <h4> looked the right size, or an icon-only heading ships with no text at all.
This post builds a small auditor in Python using only the standard library (urllib, urllib.robotparser, xml.etree, html.parser, csv, concurrent.futures). It reads your sitemap or sitemap index, fetches every page, records each h1 to h6 in order, and flags:
- pages with no headings in the main content
- pages whose content has no
<h1> - headings that come before the
<h1> - skipped levels when going deeper (
<h2>followed directly by<h4>) - empty headings, including image-only headings with no alt text
- very long headings (usually a paragraph styled as a heading)
- the same heading text repeated on one page ("Learn more" three times)
It also prints a page's outline and writes a CSV with one row per URL.
Sources opened on 22 Nov 2026: the W3C WAI tutorial on headings, MDN's heading elements reference, WCAG technique H42 (showing "Updated 06 September 2026") and Google's SEO Starter Guide (showing "Last updated 2025-12-10 UTC"). Every statement attributed to them below comes from those pages. The output in this post comes from a small fictional invoicing app ("Quillmoor Invoicing") served on localhost, built for this article with planted problems. Appie free-tool descriptions are as of 22 Nov 2026, checked on each tool's page that day.
Disclosure: Appie.run publishes this article. One free tool mentioned near the end is ours. The script does not depend on it.
Where this fits
This is another script in a small standard-library series that reads a sitemap and checks one thing per page. An earlier post on missing, empty, multiple and duplicate H1 tags suggested checking heading order as a next step. This is that step: it looks at every level, not only the <h1>.
What the guidance actually says
Accessibility guidance. The W3C WAI headings tutorial: "Skipping heading ranks can be confusing and should be avoided where possible: Make sure that a <h2> is not followed directly by an <h4>, for example. It is ok to skip ranks when closing subsections, for instance, a <h2> beginning a new section, can follow an <h4> as it closes the previous section."
It adds an exception for fixed parts of the page: "In fixed sections of the page, for example in sidebars, the heading ranks should not change depending on the ranks in the content area. In those cases, consistency across pages is more important."
MDN says the same in fewer words: "Do not skip heading levels: always start from <h1>, followed by <h2> and so on," and "Do not use heading elements to resize text." It explains why: screen reader users often jump from heading to heading, and a skipped level "may create confusion, as the person navigating this way may be left wondering where the missing heading is."
WCAG technique H42 gives the test: check that heading markup is used when content is a heading, that the level fits the content, and that heading markup is not used when content is not a heading.
Search guidance. Google's SEO Starter Guide is direct about order: "Having your headings in semantic order is fantastic for screen readers, but from Google Search perspective, it doesn't matter if you're using them out of order." It also says there is "no magical, ideal amount of headings a given page should have."
So this is mainly an accessibility and readability audit, not a ranking fix. Treat the findings that way.
How the audit works
- Read the sitemap (or every child sitemap in an index) and collect each
<loc>. - Read
robots.txtand skip disallowed URLs. - Fetch each page and walk the HTML with
html.parser, recording each heading's level, its text (an<img>inside a heading contributes itsalttext) and where it sits. - Split headings into content and chrome. Anything inside
<nav>or<aside>, or inside a<header>or<footer>that is not itself inside<main>,<article>or<section>, counts as chrome: menus, sidebars and site footers. Following the W3C exception, chrome headings are listed in the outline but not checked for skipped levels. - Run the checks on content headings, then write a CSV and print the flagged pages, most serious first.
The <header> rule matters. Many templates put the page title in <article><header><h1>…</h1></header>. That header belongs to the page, not the site, so its <h1> must count as content. My first version treated every <header> as chrome and reported a missing <h1> on every page built that way. If you adapt the script, keep that distinction.
What the script flags
| Issue | Severity | Meaning | Usual fix |
|---|---|---|---|
no_headings |
1 | No h1 to h6 in the main content |
Turn bold "fake headings" into real headings |
no_h1 |
1 | Content headings exist but none is an <h1>
|
See the H1 post |
empty_heading |
1 | A heading with no text and no image alt text | Add text, add alt, or remove the element |
skipped_level |
2 | Going deeper by more than one level, e.g. <h2> then <h4>
|
Use the next level and resize with CSS |
heading_before_h1 |
2 | A content heading appears before the <h1>
|
Make banners and labels plain elements, not headings |
long_heading |
3 | Longer than 100 characters | Usually a paragraph styled as a heading; make it a <p>
|
repeated_heading |
3 | Same text used more than once on the page | Make headings specific ("Payments setup steps", not "Learn more") |
Going back up (an <h4> followed by an <h2>) is never flagged, because that is how a section closes.
The script
Save as heading_audit.py. Python 3.8 or later, nothing to install.
#!/usr/bin/env python3
"""Audit heading structure (h1-h6) for every page in a sitemap. Standard library only.
Usage:
python3 heading_audit.py https://example.com/sitemap.xml [--csv report.csv] [--outline URL]
"""
import argparse, csv, re, sys
import urllib.request, urllib.robotparser, urllib.parse
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from html.parser import HTMLParser
UA = "heading-audit/1.0 (+standard-library script)"
SM_NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
CHROME_TAGS = {"nav", "aside"} # always page furniture
EDGE_TAGS = {"header", "footer"} # furniture only outside main/article/section
SECTION_TAGS = {"main", "article", "section"}
SKIP_TAGS = {"script", "style", "template", "noscript"}
LONG_HEADING = 100 # characters
SEVERITY = {"no_headings": 1, "no_h1": 1, "empty_heading": 1,
"skipped_level": 2, "heading_before_h1": 2,
"long_heading": 3, "repeated_heading": 3}
def fetch(url, timeout=20):
req = urllib.request.Request(url, headers={"User-Agent": UA})
with urllib.request.urlopen(req, timeout=timeout) as resp:
charset = resp.headers.get_content_charset() or "utf-8"
return resp.status, resp.headers.get("Content-Type", ""), resp.read().decode(charset, "replace")
def sitemap_urls(sitemap_url):
"""Return every <loc> in a sitemap, following a sitemap index one level down."""
_, _, body = fetch(sitemap_url)
root = ET.fromstring(body.encode("utf-8"))
if root.tag == SM_NS + "sitemapindex":
urls = []
for loc in root.iter(SM_NS + "loc"):
urls.extend(sitemap_urls(loc.text.strip()))
return urls
return [loc.text.strip() for loc in root.iter(SM_NS + "loc")]
class HeadingParser(HTMLParser):
"""Collect headings in document order with their level, text and region."""
def __init__(self):
super().__init__(convert_charrefs=True)
self.headings = [] # dicts: level, text, region
self._chrome = 0 # depth inside nav/aside, or a site-level header/footer
self._section = 0 # depth inside main/article/section
self._edge_stack = [] # for each open header/footer: did it count as chrome?
self._skip = 0
self._current = None
def handle_starttag(self, tag, attrs):
if tag in SKIP_TAGS:
self._skip += 1
elif tag in SECTION_TAGS:
self._section += 1
elif tag in CHROME_TAGS:
self._chrome += 1
elif tag in EDGE_TAGS:
is_chrome = self._section == 0 # a <header> inside <main> is the page's own header
self._edge_stack.append(is_chrome)
self._chrome += is_chrome
elif re.fullmatch(r"h[1-6]", tag):
self._current = {"level": int(tag[1]), "text": "",
"region": "chrome" if self._chrome else "content"}
elif tag == "img" and self._current is not None:
alt = dict(attrs).get("alt") or ""
self._current["text"] += " " + alt # an image's alt text is its accessible name
def handle_endtag(self, tag):
if tag in SKIP_TAGS and self._skip:
self._skip -= 1
elif tag in SECTION_TAGS and self._section:
self._section -= 1
elif tag in CHROME_TAGS and self._chrome:
self._chrome -= 1
elif tag in EDGE_TAGS and self._edge_stack:
self._chrome -= self._edge_stack.pop()
elif re.fullmatch(r"h[1-6]", tag) and self._current is not None:
self._current["text"] = " ".join(self._current["text"].split())
self.headings.append(self._current)
self._current = None
def handle_data(self, data):
if self._current is not None and not self._skip:
self._current["text"] += data
def check(headings):
"""Return a list of (issue, detail) for one page."""
issues = []
content = [h for h in headings if h["region"] == "content"]
for h in headings:
if not h["text"]:
where = "" if h["region"] == "content" else " (in header/nav/aside/footer)"
issues.append(("empty_heading", f"empty <h{h['level']}>{where}"))
if not content:
issues.append(("no_headings", "no h1-h6 in the main content"))
return issues
levels = [h["level"] for h in content]
if 1 not in levels:
issues.append(("no_h1", f"content starts at <h{levels[0]}>"))
else:
before = [h for h in content[: levels.index(1)]]
for h in before:
issues.append(("heading_before_h1", f"<h{h['level']}> \"{h['text'][:60]}\" comes before the <h1>"))
for prev, cur in zip(content, content[1:]):
if cur["level"] > prev["level"] + 1: # going deeper by more than one rank
issues.append(("skipped_level",
f"<h{prev['level']}> \"{prev['text'][:40]}\" -> <h{cur['level']}> \"{cur['text'][:40]}\""))
for h in content:
if len(h["text"]) > LONG_HEADING:
issues.append(("long_heading", f"<h{h['level']}> is {len(h['text'])} characters"))
seen = {}
for h in content:
key = h["text"].lower()
if key:
seen[key] = seen.get(key, 0) + 1
for text, count in seen.items():
if count > 1:
issues.append(("repeated_heading", f"\"{text[:60]}\" used {count} times"))
return issues
def audit(url):
try:
status, ctype, body = fetch(url)
except Exception as exc: # network errors, 4xx, 5xx
return {"url": url, "status": getattr(exc, "code", "error"), "headings": [],
"issues": [("fetch_failed", str(exc)[:80])]}
if "html" not in ctype:
return {"url": url, "status": status, "headings": [], "issues": [("not_html", ctype)]}
parser = HeadingParser()
parser.feed(body)
return {"url": url, "status": status, "headings": parser.headings, "issues": check(parser.headings)}
def print_outline(result):
print(f"Outline for {result['url']}")
for h in result["headings"]:
mark = " [chrome]" if h["region"] == "chrome" else ""
print(f"{' ' * (h['level'] - 1)}h{h['level']}: {h['text'] or '(empty)'}{mark}")
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("sitemap")
ap.add_argument("--csv", default="heading_report.csv")
ap.add_argument("--outline", help="print the heading outline of one URL from the sitemap")
ap.add_argument("--workers", type=int, default=4)
args = ap.parse_args()
robots = urllib.robotparser.RobotFileParser()
robots.set_url(urllib.parse.urljoin(args.sitemap, "/robots.txt"))
try:
robots.read()
except Exception:
robots = None
urls = sitemap_urls(args.sitemap)
allowed = [u for u in urls if robots is None or robots.can_fetch(UA, u)]
print(f"Sitemap URLs: {len(urls)} allowed by robots.txt: {len(allowed)}")
with ThreadPoolExecutor(max_workers=args.workers) as pool:
results = list(pool.map(audit, allowed))
flagged = [r for r in results if r["issues"]]
print(f"Pages with heading issues: {len(flagged)} of {len(results)}\n")
for r in sorted(flagged, key=lambda r: min(SEVERITY.get(i, 1) for i, _ in r["issues"])):
print(r["url"])
for issue, detail in sorted(r["issues"], key=lambda x: SEVERITY.get(x[0], 1)):
print(f" [{issue}] {detail}")
counts = {}
for r in results:
for issue, _ in r["issues"]:
counts[issue] = counts.get(issue, 0) + 1
if counts:
print("\nTotals: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items(), key=lambda kv: SEVERITY.get(kv[0], 1))))
with open(args.csv, "w", newline="", encoding="utf-8") as fh:
w = csv.writer(fh)
w.writerow(["url", "status", "headings", "content_outline", "issues"])
for r in results:
outline = " > ".join(f"h{h['level']}" for h in r["headings"] if h["region"] == "content")
w.writerow([r["url"], r["status"], len(r["headings"]), outline,
"; ".join(f"{i}: {d}" for i, d in r["issues"])])
print(f"\nCSV written: {args.csv}")
if args.outline:
match = next((r for r in results if r["url"] == args.outline), None)
if match:
print()
print_outline(match)
if __name__ == "__main__":
sys.exit(main())
Running it against a test site
The test site is a fictional invoicing app with nine pages, served from a folder with python3 -m http.server 8772. The site menu has a visually hidden <h2> in the site <header>, some pages have a sidebar <aside> with an <h4>, and every page has a site <footer> with an <h5>. The planted problems are in the main content:
-
/features/jumps from<h2>to<h4>, and later from<h3>to<h5> -
/pricing/has a promo banner marked up as an<h3>above the<h1> -
/blog/how-to-chase-late-invoices/has an empty<h2>and an<h2>holding only an icon with noalt -
/integrations/has a 167-character<h2>and three<h3>Learn more</h3> -
/terms/uses bold paragraphs instead of headings
python3 heading_audit.py http://localhost:8772/sitemap.xml \
--csv heading_report_before.csv \
--outline http://localhost:8772/features/
Output:
Sitemap URLs: 9 allowed by robots.txt: 9
Pages with heading issues: 5 of 9
http://localhost:8772/blog/how-to-chase-late-invoices/
[empty_heading] empty <h2>
[empty_heading] empty <h2>
http://localhost:8772/terms/
[no_headings] no h1-h6 in the main content
http://localhost:8772/features/
[skipped_level] <h2> "Invoices" -> <h4> "Recurring invoices"
[skipped_level] <h3> "Aging report" -> <h5> "Export to CSV"
http://localhost:8772/pricing/
[heading_before_h1] <h3> "Black Friday: 30% off annual plans" comes before the <h1>
http://localhost:8772/integrations/
[long_heading] <h2> is 167 characters
[repeated_heading] "learn more" used 3 times
Totals: empty_heading 2, no_headings 1, skipped_level 2, heading_before_h1 1, long_heading 1, repeated_heading 1
CSV written: heading_report_before.csv
Outline for http://localhost:8772/features/
h2: Site menu [chrome]
h1: Features
h2: Invoices
h4: Recurring invoices
h4: Multi-currency
h2: Reports
h3: Aging report
h5: Export to CSV
h4: Popular guides [chrome]
h5: Quillmoor Invoicing [chrome]
Things to notice:
- The icon-only heading on the blog post shows up as the second
empty_heading. To a screen reader, an<h2>holding an image with noalthas no name. - The site menu's
<h2>sits above the<h1>on every page but is not flagged, because it is inside the site<header>. The sidebar<h4>and footer<h5>are not flagged as skipped levels either. They are tagged[chrome]in the outline so you can still see them. - On
/features/, the jump from<h4> Multi-currencyback up to<h2> Reportsis not flagged, because closing a section is allowed. - The blog post at
/blog/agency-payment-terms/puts its<h1>inside<article><header>, and it passes.
The CSV has one row per URL with the content outline, which is handy for spotting templates at a glance:
url,status,headings,content_outline,issues
http://localhost:8772/,200,7,h1 > h2 > h2 > h3 > h3,
http://localhost:8772/features/,200,10,h1 > h2 > h4 > h4 > h2 > h3 > h5,"skipped_level: <h2> ""Invoices"" -> <h4> ""Recurring invoices""; skipped_level: <h3> ""Aging report"" -> <h5> ""Export to CSV"""
Fixing it and running again
The fixes on the test site:
-
/features/: the<h4>items became<h3>, and the<h5>became<h4>. The visual size is a CSS job. -
/pricing/: the banner became<p class="promo-title">. -
/blog/how-to-chase-late-invoices/: the empty heading got real text, and the icon gotalt="Day 7: a second reminder". -
/integrations/: the long heading became a lead paragraph, and each "Learn more" became a specific heading. -
/terms/: bold paragraphs became an<h1>and<h2>headings.
Second run:
python3 heading_audit.py http://localhost:8772/sitemap.xml \
--csv heading_report_after.csv \
--outline http://localhost:8772/blog/agency-payment-terms/
Sitemap URLs: 9 allowed by robots.txt: 9
Pages with heading issues: 0 of 9
CSV written: heading_report_after.csv
Outline for http://localhost:8772/blog/agency-payment-terms/
h2: Site menu [chrome]
h1: Payment terms for agencies: net 15, net 30 or upfront?
h2: Net 15
h2: Net 30
h3: When net 30 makes sense
h2: Deposits and upfront payment
h4: Popular guides [chrome]
h5: Quillmoor Invoicing [chrome]
Running it on your own site
-
Start with one template. Headings usually come from templates, so one fix often clears hundreds of pages. Sort the CSV by
content_outlineto group pages built the same way. -
Be polite. The default is 4 workers. Lower it with
--workers 2on a small server, and run it outside peak hours. -
JavaScript-rendered pages. The script reads the HTML your server sends. If headings are added in the browser, it will report
no_headings. Check one page in your browser's accessibility tree before trusting that result. -
Visually hidden headings. A hidden
<h2>for the menu (like the test site's) is a common accessibility pattern. The script does not read CSS, so it cannot tell visible from hidden; it relies on the element being inside<nav>or a site<header>. -
Adjust the thresholds.
LONG_HEADING = 100is my choice, not a standard. Change it to suit your content.
What to fix first
- Empty headings. They are announced as nothing, which is the most confusing result for a screen reader user.
-
Pages with no headings, or no
<h1>. Readers lose the page's main topic and structure. - Skipped levels in templates. One template fix covers every page that uses it.
-
Headings before the
<h1>. Usually banners and labels. Make them plain elements. - Long and repeated headings. Lower priority, but they make the outline harder to scan.
Related free tool
If you want a quick list of the URLs you are about to audit, our free Sitemap URL Extractor gives you one URL per line from a sitemap. For a sitemap index it lists the child sitemaps, which you then run one at a time. It does not check headings; that is what the script is for.
FAQ
Does heading order affect Google rankings?
Google's SEO Starter Guide says headings in semantic order are "fantastic for screen readers, but from Google Search perspective, it doesn't matter if you're using them out of order." Fix order for readers, not for rankings.
Is skipping a heading level an accessibility failure?
The W3C WAI tutorial says skipping ranks "can be confusing and should be avoided where possible," and MDN says not to skip levels. WCAG technique H42 asks that the heading level fits the content. Treat skips as issues to fix.
Is it OK to go from an <h4> back to an <h2>?
Yes. The W3C tutorial says it is fine to skip ranks when closing subsections. The script only flags skips when going deeper.
Why are sidebar and footer headings not checked?
The W3C tutorial says headings in fixed sections like sidebars should stay consistent across pages rather than follow the content area. The script lists them as [chrome] in the outline and only checks them for empty text.
Can a heading contain only an image?
Yes, if the image has alt text, which becomes the heading's text. Without alt, the heading is empty to assistive technology, and the script flags it.
If you want to see every URL in a sitemap before you run audits like this one, our free Sitemap URL Extractor lists them in one step.
RG, Founder, Appie.run
Top comments (0)