Sub topic 12
Audit and Test Your Page Structure
This chapter assumes you have read the earlier chapters and can write semantic HTML. You should know heading levels, ordered and unordered lists, data tables with captions and header cells, and optional JSON-LD. You also need basic Python for the scripts. Here you will check a finished page against those rules, with a script and with manual checks, and keep the page from regressing.
What an audit is for
An audit finds places where the page's structure does not say what its visual design suggests. A page can look well organized and still be a pile of styled div elements. A retrieval system sees the markup, not your CSS.
The audit has three goals:
- Find structural defects: a second h1, skipped heading levels, tables without header cells, fake lists.
- Find content defects that markup cannot show: a section that opens with background instead of the answer, or one that only makes sense after reading the previous section.
- Make the first two repeatable, so a later edit does not undo the fix.
Automated checks are good at the first goal. People are needed for the second. The third needs a place to run the script, such as a test suite.
Automated checks with a script
You can check the heading outline, table markup and some list problems from the HTML alone. The script below extends the outline parser from earlier in the tutorial, using only the standard library. It checks these things:
- A page has exactly one h1.
- The first heading is an h1.
- No heading level is skipped.
- No heading is empty or generic.
- Every table has a caption, header cells, a
scopeon each header cell, and no merged cells. - No paragraph starts with a typed bullet character.
from html.parser import HTMLParser
GENERIC = {"overview", "introduction", "details", "more", "info", "other", "misc", "read more"}
class Audit(HTMLParser):
def __init__(self):
super().__init__()
self.headings = []
self.tables = []
self.fake_bullets = 0
self._level = None
self._buf = []
self._table = None
self._in_p = False
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if len(tag) == 2 and tag[0] == "h" and tag[1] in "123456":
self._level = int(tag[1])
self._buf = []
elif tag == "table":
self._table = {"caption": False, "th": 0, "unscoped": 0, "merged": False}
self.tables.append(self._table)
elif tag == "p":
self._in_p = True
if self._table is not None:
if tag == "caption":
self._table["caption"] = True
if tag == "th":
self._table["th"] += 1
if "scope" not in attrs:
self._table["unscoped"] += 1
if tag in ("td", "th") and ("colspan" in attrs or "rowspan" in attrs):
self._table["merged"] = True
def handle_data(self, data):
if self._level:
self._buf.append(data)
if self._in_p and data.lstrip().startswith(("•", "- ", "* ")):
self.fake_bullets += 1
def handle_endtag(self, tag):
if self._level and tag == "h" + str(self._level):
self.headings.append((self._level, "".join(self._buf).strip()))
self._level = None
elif tag == "table":
self._table = None
elif tag == "p":
self._in_p = False
def findings(audit):
problems = []
h1_count = sum(1 for level, _ in audit.headings if level == 1)
if h1_count != 1:
problems.append(f"Expected exactly one h1, found {h1_count}")
if audit.headings and audit.headings[0][0] != 1:
problems.append(f"First heading is h{audit.headings[0][0]}, not h1")
for (prev, prev_text), (cur, text) in zip(audit.headings, audit.headings[1:]):
if cur > prev + 1:
problems.append(f'Skipped level: h{prev} "{prev_text}" is followed by h{cur} "{text}"')
for level, text in audit.headings:
if not text:
problems.append(f"Empty heading: h{level}")
elif text.lower() in GENERIC:
problems.append(f'Generic heading: h{level} "{text}"')
for i, table in enumerate(audit.tables, start=1):
if not table["caption"]:
problems.append(f"Table {i}: no caption")
if table["th"] == 0:
problems.append(f"Table {i}: no header cells")
elif table["unscoped"]:
problems.append(f"Table {i}: {table['unscoped']} header cell(s) without scope")
if table["merged"]:
problems.append(f"Table {i}: merged cells")
if audit.fake_bullets:
problems.append(f"{audit.fake_bullets} paragraph(s) start with a typed bullet character")
return problems
PAGE = """
<h1>Router Guide</h1>
<h3>Overview</h3>
<p>• Restart first</p>
<h2></h2>
<table><tr><td>Plan</td><td colspan="2">Price</td></tr></table>
<h1>Extra</h1>
"""
audit = Audit()
audit.feed(PAGE)
for problem in findings(audit):
print("-", problem)Running it prints:
- Expected exactly one h1, found 2
- Skipped level: h1 "Router Guide" is followed by h3 "Overview"
- Generic heading: h3 "Overview"
- Empty heading: h2
- Table 1: no caption
- Table 1: no header cells
- Table 1: merged cells
- 1 paragraph(s) start with a typed bullet characterWhat the script cannot see
The script reads source HTML. Many sites build the page in the browser with JavaScript, so the file you fetch may hold none of the real content. For those pages, audit the rendered DOM instead. In browser developer tools, copy the outer HTML of the html element after the page has loaded, save it, and feed that to the script.
The checks are also shallow. The script catches <p>• Restart first</p>, but not a list built from div elements with CSS bullets. It catches a table with no header cells, but not a table that holds layout rather than data. Treat a clean report as "no known mechanical defects", not as "good structure".
Checking structured data
If the page carries JSON-LD, check two things. The JSON must parse, and the text in it must match the visible page. A mismatch is the most likely defect. It happens when someone edits the answer on the page and forgets the copy in the script block.
import json
import re
def jsonld_blocks(html):
pattern = r'<script type="application/ld\+json">(.*?)</script>'
return [json.loads(block) for block in re.findall(pattern, html, re.S)]
def visible_text(html):
html = re.sub(r"<script.*?</script>", "", html, flags=re.S)
html = re.sub(r"<[^>]+>", " ", html)
return " ".join(html.split())
def unmatched_faq_text(html):
visible = visible_text(html)
missing = []
for block in jsonld_blocks(html):
if block.get("@type") != "FAQPage":
continue
for question in block.get("mainEntity", []):
for text in (question["name"], question["acceptedAnswer"]["text"]):
if text not in visible:
missing.append(text)
return missing
PAGE = """
<h2>What does a factory reset do?</h2>
<p>It erases all saved settings.</p>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [{
"@type": "Question",
"name": "What does a factory reset do?",
"acceptedAnswer": {
"@type": "Answer",
"text": "It erases all saved settings and restores the default configuration."
}
}]
}
</script>
"""
print(unmatched_faq_text(PAGE))The output is a list with one string, the JSON-LD answer that does not appear on the page:
['It erases all saved settings and restores the default configuration.']This check demands an exact string match. HTML entities such as & and differences in quote style will produce false alarms, so read each reported string before you act on it. The regular expression also expects the exact <script type="application/ld+json"> opening tag. Use a real HTML parser if your templates write the tag differently.
For schema correctness, use an external validator. The Schema Markup Validator and Google's Rich Results Test check property names and types, which this script does not.
Manual checks
Some defects need a human reader. Run these checks on every important page.
- Outline view. Open the browser's accessibility tree or use a headings-list extension. Read only the headings from top to bottom. If they do not tell the story of the page, rewrite them.
- Disable CSS. Turn styles off, or use a text-only browser. Visual-only structure, such as bold text that acts as a heading, becomes obvious.
- Cold-read a section. Copy one section into an empty document. Check that its first sentence answers the heading, and that pronouns and phrases like "as above" still make sense.
- Compare source to render. View the page source and the rendered page side by side. Look for content that appears only after a click, a scroll, or a script.
- Read the tables aloud. For each table, read one cell together with its row and column headers. If the sentence is unclear, the headers or units need work.
Testing with real questions
You can also test the page with an AI answer tool. Write the questions your sections are meant to answer, ask them, and note whether your page is cited and which passage was used. The method is useful but noisy. Answers vary between runs, tools and over time, so one run proves little. Record the date, the tool and the question, and compare across several runs.
Choosing the right check
| Problem | Best check | Why |
|---|---|---|
| Second h1 or skipped level | Script | The outline is fully machine-readable. |
| Table without header cells | Script | The markup is present or absent. |
| Vague heading such as "Overview" | Script, then human | A word list finds common cases, but only a person can judge the rest. |
| Section that buries its answer | Manual cold-read | Judging the answer needs meaning. |
| JSON-LD that differs from the page | Script plus validator | Text comparison is mechanical, and schema rules need a validator. |
| Content missing from the source | Rendered-DOM comparison | Source and rendered HTML differ. |
| Citation behavior | Repeated real queries | Only an actual tool shows what it does. |
Keep the audit running
A one-time audit decays. Editors add sections, templates change, and a new campaign banner introduces a second h1. Put the script in your test suite or build pipeline so that it fails the build when it finds a problem. Save the code above as audit_page.py, then add a test file:
from audit_page import Audit, findings
def test_guide_structure():
with open("public/guide.html", encoding="utf-8") as handle:
audit = Audit()
audit.feed(handle.read())
assert findings(audit) == []Sort what the audit finds before you fix it. Fix problems that change the document's meaning first: a missing h1, headings that skip levels, and tables without header cells. Fix cosmetic ones, such as a generic heading on a minor page, later. If the script flags a deliberate exception, such as a layout table you cannot remove, record the exception in the test and do not delete the check.
Common audit errors
- Auditing only the template. The template may be clean while article bodies, written by editors, contain the defects. Audit sampled content pages, not just the shell.
- Counting headings in navigation and footers. Menus and cookie banners often contain headings. They count toward your outline, so decide whether to demote them or remove their heading tags.
- Trusting the source of a client-rendered page. If the fetched HTML is nearly empty, the script is auditing nothing.
- Fixing the report and not the page. Adding
scopeattributes to silence the script is fine. Adding a caption such as "Table" is not. The check passes while the problem remains. - Treating one test query as evidence. A single cited or uncited result says little about the page.
Exercise
A page's source HTML contains one h1, an h2, and an h3 in order, and the script reports no problems. A reader opens the page and sees the headings, but the main content is blank until a script loads it. What should you audit, and why?
Show answer
Audit the rendered DOM, not the source file. The script only saw the markup delivered before JavaScript ran, so a clean report says nothing about the content users and many crawlers see after rendering. Save the rendered outer HTML from developer tools and run the script on that, then compare the two outlines.
Exercise
The script reports "Table 1: no caption" for a table, and a colleague proposes adding the caption "Table". Explain why this fixes the report without fixing the page, and write a better caption for a table comparing the Basic and Team plans by monthly price and number of users.
Show answer
A caption of "Table" satisfies the check but tells a reader or a retrieval system nothing about what the table holds, so the real problem, an undescribed table, remains. A better caption is "Plan comparison: monthly price and number of users for the Basic and Team plans".
Exercise
Your JSON-LD check lists one string as missing from the visible page. Give two possible causes that do not mean the page is wrong, and one that does.
Show answer
The first two causes are false alarms. The page may write "&" where the JSON-LD has "&", or it may differ only in whitespace or quote style, so the exact comparison fails. The third cause is a real defect: someone edited the visible answer and not the JSON-LD (or the reverse), so the structured data now describes content readers cannot see. Fix this by making both copies match.