AI 編碼生成的網站可能對爬蟲呈現空白頁,Vincent 分享 crawler_view.py 檢查器
Your Vibe-Coded Site Is a Blank Page to Crawlers. I Wrote a Checker.
Vincent 編寫 crawler_view.py,檢查未執行 JavaScript 時原始 HTML 的標題、可見字數、空白 root,以及 JSON-LD 資料是否也出現在頁面文字中。
This week on X, someone described a plumbing company's AI-built site: real service pages, six blocks of structured data, and a blank page to any crawler that didn't run JavaScript. That is the same shape I keep seeing when a marketing site comes out of a coding agent as a Vite + React app and ships with the default index.html.
The title is still Vite + React. The body is <div id="root"></div>. The services, the phone number, the reviews, and the JSON-LD all live in a useEffect. curl sees none of it. Chrome looks finished, so nobody notices until Search Console or an assistant-search result comes back empty.
Googlebot can render JavaScript, but it does not always wait, and the first look at the response is still the raw HTML. A lot of AI crawlers are closer to curl than to a full browser. Social previews are too: Slack, LinkedIn and X read the HTML you sent, not the tree React built after hydration.
It doesn't matter whether the site came from Cursor, Claude Code or an AI website builder. If the HTML response is a shell, this applies.
So I wrote the kind of site a coding agent produces for "a roofing company in Denver with services, reviews and a quote form." Then I wrote a short checker, crawler_view.py, that reads the raw HTML — no JavaScript — and reports the title, the visible word count, whether #root is empty, and whether any JSON-LD facts are missing from the visible text. I ran it on the shell, on a prerendered page that still invented 214 reviews, and on a prerendered page that only marks up what's on the page. All the numbers below come from those three runs.
The fixture
The business is fictional. It's called Redbird Roofing, and it does residential roof repair in Denver. The "before" repo looks like a typical generated SPA: a Vite index.html and a React tree that injects both the page and the schema in the browser.
Here is the file that actually gets deployed, before any prerender step. This is the whole document.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
<script type="module" src="/src/main.jsx"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
The useful page lives in App.jsx. A useEffect appends the JSON-LD after mount. That includes an aggregateRating of 4.9 from 214 reviews, because the prompt asked for reviews and the model is happy to invent a number that looks like social proof.
// Excerpt from the fixture. Deliberately typical of a generated marketing SPA.
useEffect(() => {
const el = document.createElement("script");
el.type = "application/ld+json";
el.text = JSON.stringify(schema); // includes aggregateRating 4.9 / 214
document.head.appendChild(el);
}, []);
If you open the site in a browser, you see a roofing company. If you view source, you see an empty root and a scaffolding title.
The checker
crawler_view.py reads a local HTML file — or an index.html under public/, dist/ or build/ — and parses it with the standard library. It does not execute JavaScript, so the report is what curl, a basic crawler, or the first look at a response body can see.
It reports:
- the
<title>and meta description - any
<h1>in the raw HTML - a visible word count, with
scriptandstyleremoved (a<noscript>block does count, because a no-JS client can read it) - empty app shells:
#root,#app,#__next,#__nuxtwith almost no text inside - every
application/ld+jsonblock, its types, and whether telephone, address, price,ratingValueandreviewCountalso appear in the visible text
Default titles it treats as scaffolding include Vite + React, Create Next App, React App and a few cousins. A US phone number in schema may be written as +1-303-555-0148 while the page shows (303) 555-0148; the checker compares digits, not punctuation.
It does not render the page, does not claim to be Google's renderer, and does not fetch a live site. Point it at an HTML file you already have, including a response you saved with curl -o page.html https://yoursite.example/.
crawler_view.py (about 400 lines, 12 tests)
#!/usr/bin/env python3
"""crawler_view.py — show what of a page is visible without running JavaScript.
Usage:
python3 crawler_view.py fixtures/before
python3 crawler_view.py path/to/index.html
python3 crawler_view.py --self-test
Reads the raw HTML (a local file, or a directory containing index.html,
public/index.html or dist/index.html). It does not execute JavaScript, so
the report is what a curl, a basic crawler, or Google's first look at the
response body can see.
Findings:
default title — Vite + React, Create Next App, and similar scaffolding
crawler-blank — almost no visible text, often an empty #root / #app
missing H1 — no <h1> in the raw HTML
no JSON-LD — no application/ld+json block in the raw HTML
invented schema — JSON-LD facts that do not appear in the visible text
This does not render the page, does not claim to be Google's renderer, and
does not fetch a live site unless you pass a raw HTML file you already saved.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import unittest
from dataclasses import dataclass, field
from html.parser import HTMLParser
from pathlib import Path
DEFAULT_TITLES = {
"vite + react",
"vite + vue",
"vite + svelte",
"vite app",
"vite",
"react app",
"create next app",
"create react app",
"next.js",
"document",
"nuxt",
"nuxt app",
"sveltekit",
"astro",
"welcome to vite",
"just a moment...",
"just a moment…",
}
ROOT_IDS = {"root", "app", "__next", "__nuxt"}
SKIP_TAGS = {"script", "style", "template", "noscript"}
# noscript is visible to a no-JS client, so it is NOT skipped for text.
SKIP_TAGS = {"script", "style", "template"}
WORD_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9'’.-]*")
PHONE_RE = re.compile(r"\+?\d[\d\-().\s]{6,}\d")
BLANK_THRESHOLD = 40
# JSON-LD keys whose values should also be visible on the page.
FACT_KEYS = {
"telephone": "telephone",
"phone": "telephone",
"email": "email",
"streetaddress": "street address",
"addresslocality": "city",
"addressregion": "region",
"postalcode": "postal code",
"ratingvalue": "ratingValue",
"reviewcount": "reviewCount",
"ratingcount": "ratingCount",
"pricecurrency": "priceCurrency",
"price": "price",
"lowprice": "lowPrice",
"highprice": "highPrice",
}
@dataclass
class SchemaFact:
key: str
label: str
value: str
visible: bool
kind: str # "text" | "phone" | "rating" | "count" | "price"
@dataclass
class Report:
path: Path
title: str = ""
meta_description: str = ""
h1s: list[str] = field(default_factory=list)
visible_text: str = ""
word_count: int = 0
empty_roots: list[str] = field(default_factory=list)
jsonld_blocks: list[object] = field(default_factory=list)
jsonld_types: list[str] = field(default_factory=list)
jsonld_errors: list[str] = field(default_factory=list)
facts: list[SchemaFact] = field(default_factory=list)
findings: list[str] = field(default_factory=list)
@property
def invented(self) -> list[SchemaFact]:
return [f for f in self.facts if not f.visible]
class PageParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.title_parts: list[str] = []
self.meta_description = ""
self.h1s: list[str] = []
self._h1_buf: list[str] = []
self.visible: list[str] = []
self.ldjson: list[str] = []
self._ld_buf: list[str] = []
self.skip = 0
self.in_title = 0
self.in_h1 = 0
self.in_ld = 0
self.in_head = 0
self.root_text: dict[str, list[str]] = {}
self._root_stack: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "head":
self.in_head += 1
ad = {k.lower(): (v or "") for k, v in attrs}
if tag == "meta":
name = ad.get("name", "").lower()
prop = ad.get("property", "").lower()
if name == "description" or prop == "og:description":
if ad.get("content") and not self.meta_description:
self.meta_description = ad["content"].strip()
if tag == "title":
self.in_title += 1
if tag == "h1":
self.in_h1 += 1
self._h1_buf = []
if tag == "script":
typ = ad.get("type", "").lower()
if typ in {"application/ld+json", "application/json+ld"}:
self.in_ld += 1
self._ld_buf = []
else:
self.skip += 1
return
if tag in SKIP_TAGS:
self.skip += 1
return
eid = ad.get("id", "")
if eid in ROOT_IDS:
self._root_stack.append(eid)
self.root_text.setdefault(eid, [])
def handle_endtag(self, tag: str) -> None:
if tag == "head" and self.in_head:
self.in_head -= 1
if tag == "title" and self.in_title:
self.in_title -= 1
if tag == "h1" and self.in_h1:
self.in_h1 -= 1
text = _norm("".join(self._h1_buf))
if text:
self.h1s.append(text)
self._h1_buf = []
if tag == "script" and self.in_ld:
self.in_ld -= 1
self.ldjson.append("".join(self._ld_buf))
self._ld_buf = []
return
if tag in SKIP_TAGS or tag == "script":
if self.skip:
self.skip -= 1
return
if self._root_stack and tag in {"div", "main", "app"}:
# pop only when this end tag likely closes the root we opened.
# HTMLParser doesn't give us identity; we pop if the top root
# already received some end of a container. Safer: only pop on
# explicit close of div when stack is non-empty and skip==0.
pass
def handle_data(self, data: str) -> None:
if self.in_ld:
self._ld_buf.append(data)
return
if self.skip:
return
if self.in_title:
self.title_parts.append(data)
if self.in_h1:
self._h1_buf.append(data)
# Title, meta and other head text are not page body.
if self.in_head or self.in_title:
return
self.visible.append(data)
for rid in self._root_stack:
self.root_text[rid].append(data)
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
self.handle_endtag(tag)
def _norm(s: str) -> str:
return re.sub(r"\s+", " ", s).strip()
def _words(s: str) -> list[str]:
return WORD_RE.findall(s)
def _digits(s: str) -> str:
return re.sub(r"\D+", "", s)
def _national_phone(s: str) -> str:
"""Best-effort national number: strip a leading country code 1 from NANP numbers."""
d = _digits(s)
if len(d) == 11 and d.startswith("1"):
return d[1:]
return d
def resolve_html(target: str) -> Path:
p = Path(target)
if p.is_file():
return p
if not p.is_dir():
raise SystemExit(f"not a file or directory: {p}")
for cand in (
p / "index.html",
p / "public" / "index.html",
p / "dist" / "index.html",
p / "out" / "index.html",
p / "build" / "index.html",
):
if cand.is_file():
return cand
raise SystemExit(f"no index.html under {p}")
def _collect_types(node: object, out: list[str]) -> None:
if isinstance(node, list):
for item in node:
_collect_types(item, out)
return
if not isinstance(node, dict):
return
typ = node.get("@type")
if isinstance(typ, list):
out.extend(str(t) for t in typ)
elif typ:
out.append(str(typ))
graph = node.get("@graph")
if graph:
_collect_types(graph, out)
for key, val in node.items():
if key in {"@type", "@graph"}:
continue
if isinstance(val, (dict, list)):
_collect_types(val, out)
def _walk_facts(node: object, out: list[tuple[str, str]]) -> None:
if isinstance(node, list):
for item in node:
_walk_facts(item, out)
return
if not isinstance(node, dict):
return
for key, val in node.items():
if key.startswith("@"):
if key == "@graph":
_walk_facts(val, out)
continue
lk = key.lower()
if lk in FACT_KEYS and isinstance(val, (str, int, float)):
out.append((lk, str(val).strip()))
elif isinstance(val, (dict, list)):
_walk_facts(val, out)
def _fact_visible(key: str, value: str, visible: str, visible_digits: str) -> tuple[bool, str, str]:
label = FACT_KEYS[key]
if key in {"telephone", "phone"}:
digits = _digits(value)
national = _national_phone(value)
ok = len(national) >= 7 and (national in visible_digits or digits in visible_digits)
return ok, label, "phone"
if key in {"ratingvalue", "reviewcount", "ratingcount"}:
# The exact number must appear in the visible text.
compact = value.replace(",", "").strip()
ok = bool(re.search(rf"(?<![\d.]){re.escape(compact)}(?![\d.])", visible.replace(",", "")))
kind = "rating" if key == "ratingvalue" else "count"
return ok, label, kind
if key in {"price", "lowprice", "highprice"}:
compact = value.replace(",", "").strip()
ok = compact in visible.replace(",", "")
return ok, label, "price"
# Address / email / currency: case-insensitive substring.
ok = value.lower() in visible.lower()
return ok, label, "text"
def inspect(path: Path) -> Report:
raw = path.read_text(encoding="utf-8", errors="replace")
parser = PageParser()
parser.feed(raw)
parser.close()
title = _norm("".join(parser.title_parts))
visible = _norm("".join(parser.visible))
words = _words(visible)
report = Report(
path=path,
title=title,
meta_description=_norm(parser.meta_description),
h1s=parser.h1s,
visible_text=visible,
word_count=len(words),
)
for rid, parts in parser.root_text.items():
text = _norm("".join(parts))
if len(_words(text)) <= 3:
report.empty_roots.append(rid)
visible_digits = _digits(visible)
for chunk in parser.ldjson:
text = chunk.strip()
if not text:
continue
try:
data = json.loads(text)
except json.JSONDecodeError as exc:
report.jsonld_errors.append(f"invalid JSON-LD: {exc.msg}")
continue
report.jsonld_blocks.append(data)
types: list[str] = []
_collect_types(data, types)
for t in types:
if t not in report.jsonld_types:
report.jsonld_types.append(t)
found: list[tuple[str, str]] = []
_walk_facts(data, found)
for key, value in found:
if not value:
continue
ok, label, kind = _fact_visible(key, value, visible, visible_digits)
report.facts.append(SchemaFact(key, label, value, ok, kind))
# Findings, in a stable order.
if title.lower() in DEFAULT_TITLES or not title:
report.findings.append("default title")
# A JS shell is usually an empty #root with almost no body text.
# A short but complete page (title, H1, real copy) is not a shell.
is_shell = bool(report.empty_roots) and report.word_count < 80
is_tiny = report.word_count < 12 and not report.h1s
if is_shell or is_tiny:
report.findings.append("crawler-blank")
if not report.h1s:
report.findings.append("missing H1")
if not report.jsonld_blocks:
report.findings.append("no JSON-LD")
if report.invented:
report.findings.append("invented schema")
if report.jsonld_errors:
report.findings.append("invalid JSON-LD")
return report
def format_report(report: Report) -> str:
lines: list[str] = []
lines.append(f"crawler_view.py (no JavaScript)")
lines.append(f"file: {report.path}")
lines.append("")
lines.append("PAGE")
lines.append(f" title {report.title or '(none)'}")
lines.append(f" meta description {report.meta_description or '(none)'}")
if report.h1s:
for i, h in enumerate(report.h1s, 1):
label = "H1" if i == 1 else f"H1 #{i}"
lines.append(f" {label:<18} {h}")
else:
lines.append(" H1 (none)")
lines.append(f" visible words {report.word_count}")
if report.empty_roots:
lines.append(" empty containers #" + ", #".join(report.empty_roots))
else:
lines.append(" empty containers (none)")
lines.append("")
lines.append("JSON-LD")
if report.jsonld_errors:
for err in report.jsonld_errors:
lines.append(f" error {err}")
if not report.jsonld_blocks:
lines.append(" blocks 0")
lines.append(" types (none)")
else:
lines.append(f" blocks {len(report.jsonld_blocks)}")
lines.append(" types " + ", ".join(report.jsonld_types) or "(none)")
if report.facts:
lines.append(" facts vs visible text:")
for fact in report.facts:
mark = "visible" if fact.visible else "NOT on the page"
lines.append(f" {fact.label:<16} {fact.value:<20} {mark}")
else:
lines.append(" facts (none checked)")
lines.append("")
lines.append("FINDINGS")
if report.findings:
for f in report.findings:
lines.append(f" - {f}")
else:
lines.append(" (none)")
lines.append("")
lines.append("VERDICT")
if "crawler-blank" in report.findings:
lines.append(" The raw HTML has almost no visible text.")
if report.empty_roots:
ids = ", ".join(f"#{i}" for i in report.empty_roots)
lines.append(f" {ids} is empty without JavaScript, so a crawler that does not run JS sees a shell.")
if "default title" in report.findings:
lines.append(f" The title is still {report.title!r}, which is scaffolding, not a page title.")
if "no JSON-LD" in report.findings:
lines.append(" Any schema in the React tree never reaches the HTML response.")
elif "invented schema" in report.findings:
n = len(report.invented)
lines.append(f" The page has visible content, but {n} JSON-LD fact(s) are not on the page.")
names = ", ".join(f"{f.label}={f.value}" for f in report.invented)
lines.append(f" {names}.")
lines.append(" Google's structured data guidelines say not to mark up content that is not visible.")
elif report.findings == ["no JSON-LD"]:
lines.append(" The raw HTML has a real title, an H1 and enough visible text.")
lines.append(" There is no JSON-LD in the response; add it only for facts already on the page.")
elif report.findings:
lines.append(" " + "; ".join(report.findings) + ".")
else:
lines.append(" The raw HTML has a real title, an H1 and enough visible text.")
if report.facts:
lines.append(" JSON-LD facts checked here also appear in the visible text.")
return "\n".join(lines) + "\n"
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
SHELL = """<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Vite + React</title>
<script type="module" src="/src/main.jsx"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
"""
INVENTED = """<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Redbird Roofing | Denver roof repair</title>
<meta name="description" content="Roof repair and replacement in Denver." />
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "RoofingContractor",
"name": "Redbird Roofing",
"telephone": "+1-303-555-0148",
"address": {
"@type": "PostalAddress",
"streetAddress": "14 Redbird Way",
"addressLocality": "Denver",
"addressRegion": "CO",
"postalCode": "80211"
},
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "4.9",
"reviewCount": "214",
"bestRating": "5"
}
}
</script>
</head>
<body>
<h1>Denver roof repair and replacement</h1>
<p>Redbird Roofing fixes leaks and replaces roofs for homes in Denver, Colorado.</p>
<p>Call (303) 555-0148. Visit us at 14 Redbird Way, Denver, CO 80211.</p>
</body>
</html>
"""
HONEST = """<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Redbird Roofing | Denver roof repair</title>
<meta name="description" content="Roof repair and replacement in Denver." />
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "RoofingContractor",
"name": "Redbird Roofing",
"telephone": "+1-303-555-0148",
"address": {
"@type": "PostalAddress",
"streetAddress": "14 Redbird Way",
"addressLocality": "Denver",
"addressRegion": "CO",
"postalCode": "80211"
}
}
</script>
</head>
<body>
<h1>Denver roof repair and replacement</h1>
<p>Redbird Roofing fixes leaks and replaces roofs for homes in Denver, Colorado.</p>
<p>Call (303) 555-0148. Visit us at 14 Redbird Way, Denver, CO 80211.</p>
</body>
</html>
"""
class CrawlerViewTests(unittest.TestCase):
def setUp(self) -> None:
self.tmp = Path("/tmp/crawler_view_tests")
self.tmp.mkdir(exist_ok=True)
def _write(self, name: str, html: str) -> Path:
path = self.tmp / name
path.write_text(html, encoding="utf-8")
return path
def test_shell_is_crawler_blank_with_default_title(self) -> None:
r = inspect(self._write("shell.html", SHELL))
self.assertEqual(r.title, "Vite + React")
self.assertEqual(r.word_count, 0)
self.assertIn("root", r.empty_roots)
self.assertIn("default title", r.findings)
self.assertIn("crawler-blank", r.findings)
self.assertIn("missing H1", r.findings)
self.assertIn("no JSON-LD", r.findings)
self.assertNotIn("invented schema", r.findings)
def test_invented_rating_is_flagged_when_page_has_no_reviews(self) -> None:
r = inspect(self._write("invented.html", INVENTED))
self.assertGreater(r.word_count, 20)
self.assertNotIn("crawler-blank", r.findings)
self.assertIn("RoofingContractor", r.jsonld_types)
self.assertIn("invented schema", r.findings)
missing = {(f.key, f.value) for f in r.invented}
self.assertIn(("ratingvalue", "4.9"), missing)
self.assertIn(("reviewcount", "214"), missing)
# Phone and address are on the page, so they must not be invented.
self.assertFalse(any(f.key == "telephone" and not f.visible for f in r.facts))
self.assertFalse(any(f.key == "streetaddress" and not f.visible for f in r.facts))
def test_honest_schema_has_no_findings(self) -> None:
r = inspect(self._write("honest.html", HONEST))
self.assertEqual(r.findings, [])
self.assertTrue(all(f.visible for f in r.facts))
self.assertIn("Denver roof repair and replacement", r.h1s)
def test_phone_matches_on_digits_not_formatting(self) -> None:
r = inspect(self._write("honest.html", HONEST))
phone = next(f for f in r.facts if f.key == "telephone")
self.assertTrue(phone.visible)
def test_rating_must_appear_as_the_same_number(self) -> None:
html = HONEST.replace(
"</h1>",
"</h1><p>Customers rate us 4.8 out of 5 from 12 reviews.</p>",
).replace(
'"postalCode": "80211"',
'"postalCode": "80211",\n "aggregateRating": {"@type":"AggregateRating","ratingValue":"4.9","reviewCount":"214"}',
)
r = inspect(self._write("almost.html", html))
missing = {f.key: f.value for f in r.invented}
self.assertEqual(missing.get("ratingvalue"), "4.9")
self.assertEqual(missing.get("reviewcount"), "214")
def test_visible_rating_is_accepted(self) -> None:
html = HONEST.replace(
"</h1>",
"</h1><p>Rated 4.9 from 214 reviews.</p>",
).replace(
'"postalCode": "80211"',
'"postalCode": "80211",\n "aggregateRating": {"@type":"AggregateRating","ratingValue":"4.9","reviewCount":"214"}',
)
r = inspect(self._write("matched.html", html))
self.assertNotIn("invented schema", r.findings)
def test_client_only_jsonld_in_module_script_is_invisible(self) -> None:
html = SHELL.replace(
'<script type="module" src="/src/main.jsx"></script>',
'''<script type="module">
document.getElementById("root").innerHTML = "<h1>Hi</h1>";
const s = document.createElement("script");
s.type = "application/ld+json";
s.textContent = JSON.stringify({@context:"https://schema.org",@type:"LocalBusiness",name:"X"});
document.head.appendChild(s);
</script>'''.replace("{@", "{'@").replace("@type", "'@type"), # keep as JS, not parsed as ld+json
)
# The block above is a module script, not application/ld+json, so raw HTML has none.
r = inspect(self._write("client.html", html))
self.assertEqual(r.jsonld_blocks, [])
self.assertIn("no JSON-LD", r.findings)
self.assertIn("crawler-blank", r.findings)
def test_noscript_counts_as_visible(self) -> None:
html = """<!doctype html><html><head><title>Shop</title></head>
<body><div id="root"></div>
<noscript><h1>Redbird Roofing</h1><p>%s</p></noscript>
</body></html>""" % (" ".join(["roof"] * 50))
r = inspect(self._write("noscript.html", html))
self.assertGreaterEqual(r.word_count, 50)
self.assertIn("Redbird Roofing", r.h1s)
self.assertNotIn("crawler-blank", r.findings)
def test_invalid_jsonld_is_reported(self) -> None:
html = HONEST.replace('"Redbird Roofing"', '"Redbird Roofing",') # trailing comma after name via...
# Safer: inject a broken block.
html = HONEST.replace(
"</script>",
'</script>\n<script type="application/ld+json">{not json}</script>',
)
r = inspect(self._write("badjson.html", html))
self.assertIn("invalid JSON-LD", r.findings)
self.assertTrue(r.jsonld_errors)
def test_resolve_prefers_public_index(self) -> None:
root = self.tmp / "proj"
(root / "public").mkdir(parents=True, exist_ok=True)
(root / "public" / "index.html").write_text(SHELL, encoding="utf-8")
self.assertEqual(resolve_html(str(root)), root / "public" / "index.html")
def test_loading_spinner_inside_root_still_blank(self) -> None:
html = SHELL.replace('<div id="root"></div>', '<div id="root">Loading...</div>')
r = inspect(self._write("loading.html", html))
self.assertLess(r.word_count, BLANK_THRESHOLD)
self.assertIn("crawler-blank", r.findings)
self.assertIn("root", r.empty_roots)
def test_format_report_mentions_empty_root(self) -> None:
r = inspect(self._write("shell.html", SHELL))
text = format_report(r)
self.assertIn("visible words 0", text)
self.assertIn("#root", text)
self.assertIn("Vite + React", text)
self.assertIn("almost no visible text", text)
self.assertIn("#root", text)
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("target", nargs="?", help="HTML file or directory containing index.html")
p.add_argument("--self-test", action="store_true", help="run the unit tests and exit")
args = p.parse_args(argv)
if args.self_test or args.target is None and "--self-test" in (argv or sys.argv[1:]):
suite = unittest.defaultTestLoader.loadTestsFromTestCase(CrawlerViewTests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
return 0 if result.wasSuccessful() else 1
if not args.target:
p.print_help()
return 2
path = resolve_html(args.target)
sys.stdout.write(format_report(inspect(path)))
return 0
if __name__ == "__main__":
raise SystemExit(main())
Run 1: the Vite shell
$ python3 crawler_view.py fixtures/before
crawler_view.py (no JavaScript)
file: fixtures/before/index.html
PAGE
title Vite + React
meta description (none)
H1 (none)
visible words 0
empty containers #root
JSON-LD
blocks 0
types (none)
FINDINGS
- default title
- crawler-blank
- missing H1
- no JSON-LD
VERDICT
The raw HTML has almost no visible text.
#root is empty without JavaScript, so a crawler that does not run JS sees a shell.
The title is still 'Vite + React', which is scaffolding, not a page title.
Any schema in the React tree never reaches the HTML response.
Zero words. No H1. No JSON-LD. The six-block schema in App.jsx might as well not exist for anything that doesn't run the bundle.
This is easy to miss because the failure is invisible in the tool you use all day. The tab looks right. The Lighthouse run you did in Chrome looks right. The thing that isn't right is the bytes you actually shipped.
Run 2: prerender, then invent the reviews
The first "fix" a coding agent reaches for is to keep the SPA and inject JSON-LD in useEffect. That does not change Run 1. The schema still arrives after JavaScript runs, so curl still sees an empty #root.
The fix that actually changes the report is to put the page in the HTML: a prerender, server rendering, or a site generator. I did that for Redbird Roofing. The title, the H1, the services, the phone number and the address are now in the document. I also left in the aggregateRating the agent wanted to add — 4.9 from 214 reviews — even though the page has no reviews on it.
$ python3 crawler_view.py fixtures/mid
PAGE
title Redbird Roofing | Denver roof repair and replacement
meta description Roof repair, reroofing, and leak inspections for homes in Denver, Colorado. Call Redbird Roofing at (303) 555-0148.
H1 Denver roof repair and replacement
visible words 102
empty containers (none)
JSON-LD
blocks 1
types RoofingContractor, PostalAddress, AggregateRating
facts vs visible text:
telephone +1-303-555-0148 visible
street address 14 Redbird Way visible
city Denver visible
region CO visible
postal code 80211 visible
ratingValue 4.9 NOT on the page
reviewCount 214 NOT on the page
FINDINGS
- invented schema
VERDICT
The page has visible content, but 2 JSON-LD fact(s) are not on the page.
ratingValue=4.9, reviewCount=214.
Google's structured data guidelines say not to mark up content that is not visible.
102 visible words, a real title, a real H1, and a LocalBusiness-style block whose phone and address match the page. That is progress. It is also a new problem. The rating is only in the markup.
Google's structured data guidelines are blunt about this: don't mark up content that is not visible to readers of the page. Review-star markup for reviews that are not on the page is the version that can get you into spam policy trouble, not just a missing rich result. If you have two named testimonials, put those two on the page and mark those two up. If you don't have 214 reviews to show, don't tell the crawler you do.
We treat "does the markup match the visible page?" as its own check in our GEO audit checklist, next to a rendering check that fetches the page with JavaScript off and asks whether the headings survive. The two failures here are the same failure in different clothes: the crawler is being told a story the HTML does not tell.
Run 3: only mark up what's on the page
The second rewrite dropped aggregateRating and left the RoofingContractor facts that already appear in the contact section. No other copy changed, so the visible word count stayed at 102.
$ python3 crawler_view.py fixtures/after
PAGE
title Redbird Roofing | Denver roof repair and replacement
H1 Denver roof repair and replacement
visible words 102
empty containers (none)
JSON-LD
blocks 1
types RoofingContractor, PostalAddress
facts vs visible text:
telephone +1-303-555-0148 visible
street address 14 Redbird Way visible
city Denver visible
region CO visible
postal code 80211 visible
FINDINGS
(none)
VERDICT
The raw HTML has a real title, an H1 and enough visible text.
JSON-LD facts checked here also appear in the visible text.
That's the bar. Not "has schema." "The raw HTML is a page, and the schema is a machine-readable copy of that page."
Three decisions
Once the checker has barked at you, the work is three decisions, not one "add SEO" prompt.
-
Ship HTML a crawler can read. Server-render, prerender, or use a site generator. A client-only
#rootis a tab, not a document. If you stay on a SPA, a static snapshot at build time is the minimum; injecting markup inuseEffectis not. -
Put the facts in that HTML. A real
<title>, one H1, the services, the phone number, the address, the hours. If a stranger withcurland no JavaScript can't quote your phone number, neither can a lot of the machines you care about. - Only mark up what's visible. JSON-LD is a mirror, not a place to store the better version of the story. Ratings, prices and phone numbers have to be on the page in the same numbers.
None of this replaces a full render in Google's tools. It does catch the failure I actually see on vibe-coded marketing sites, and it catches it before you point a domain at the preview. It sits next to the rest of a launch-day SEO checklist: one list checks that search engines can find the right URLs, this one checks that the URL they fetch is a page.
What we do in PolyDraft, and what we do not claim
PolyDraft is the AI website builder we work on. It publishes server-rendered HTML to your own Cloudflare account, so the document a crawler fetches is the document you can view-source, not a shell waiting on a bundle. That makes a check like this easy to run. It does not make it unnecessary. An agent can still prerender a page and then invent 214 reviews in the JSON-LD. We still run checks like these on what we ship, and you should run them on anything with your name on the domain, whoever or whatever built it.
Before you point a domain at the preview
-
curlthe URL, or use view-source, not just the browser tab. If you seeVite + Reactand an empty#root, stop there. - Confirm a real title, an H1, and enough visible copy that a stranger could tell what the business does.
- If you add JSON-LD, every rating, price and phone number in it must also be on the page. Drop
aggregateRatinguntil the reviews are visible. - Save the HTML and run
crawler_view.pyagain after the next prompt. A scan you run once is a scan that is out of date after the agent "adds SEO."
Ten minutes, all of it against HTML you already have, all of it on your own site. Cheaper than finding out from a Search Console coverage report, or from a customer who pasted your URL into ChatGPT and got an answer about a different company.
來源:DEV Community · dev.to


