Sub topic 15
Pages that need JavaScript to render
This chapter assumes you have read the chapters on fetching pages and extracting links. It also assumes you can read short Python programs and know what the DOM (the tree of elements a browser builds from HTML) is.
The problem: the HTML you fetch is not the page you see
The crawler built so far downloads the bytes the server returns and parses them. On many modern sites those bytes are a shell. A typical single-page application (SPA) returns something like this:
<body>
<div id="root"></div>
<script src="/static/app.js"></script>
</body>A browser runs app.js, which calls an API, builds the content, and inserts it into #root. Your LinkExtractor sees no anchors and no text. The crawl ends at the seed page, and nothing in the logs says it failed. The fetch returned 200, the content type was text/html, and the page had zero links.
This is a silent failure, so the first job is to detect it. The second job is to choose a cheaper fix than running a browser, when one exists.
Detecting pages that need rendering
No check is perfect, but a few signals work well together:
- Very little visible text once
script,style, andnoscriptcontent is removed. - Very few
<a href>links. - At least one script tag.
- A near-empty mount point such as
<div id="root">or<div id="app">. - A
<noscript>message such as "You need to enable JavaScript".
The probe below counts visible text, links, and scripts using only the standard library.
from html.parser import HTMLParser
SKIPPED = ('script', 'style', 'noscript')
class TextProbe(HTMLParser):
def __init__(self):
super().__init__()
self.text_chars = 0
self.links = 0
self.scripts = 0
self._skip = 0
def handle_starttag(self, tag, attrs):
if tag in SKIPPED:
self._skip += 1
if tag == 'script':
self.scripts += 1
elif tag == 'a' and any(n == 'href' and v for n, v in attrs):
self.links += 1
def handle_endtag(self, tag):
if tag in SKIPPED and self._skip:
self._skip -= 1
def handle_data(self, data):
if not self._skip:
self.text_chars += len(data.strip())
def needs_rendering(html, min_text=200, min_links=3):
probe = TextProbe()
probe.feed(html)
return (probe.scripts > 0
and probe.text_chars < min_text
and probe.links < min_links)
shell = '<body><div id="root"></div><script src="/app.js"></script></body>'
print(needs_rendering(shell)) # TrueTreat the result as a hint, not a verdict. A genuine short page, such as a redirect stub or a login form, also passes this test. The cost of a false positive is one wasted render. The cost of a false negative is a page you never see. Tune the thresholds on a sample of your own targets.
Three ways to get the content
Rendering with a full browser is the last resort. Try the cheaper options first.
| Approach | How it works | Cost | Weak point |
|---|---|---|---|
| Call the data API directly | Find the JSON endpoint the script calls and fetch it | Same as a normal fetch | Needs per-site work. Endpoints change and may need tokens |
| Read embedded state | Parse JSON placed in the HTML, such as `__NEXT_DATA__` or JSON-LD in a `<script>` tag | Same as a normal fetch | Not every site embeds data. The format varies |
| Headless browser | Run a real browser engine, wait, then read the final DOM | Roughly 10 to 100 times slower, with much more memory | Heavy, and harder to make polite |
Server-side rendering and embedded state are common because they help search engines. A page that looks empty in your parser often still has its data in a script tag. Checking for it takes a few lines and costs almost nothing.
A headless browser is a browser with no visible window, controlled from code. It is the only option that works on arbitrary sites without per-site knowledge, which is why general crawlers keep it as a fallback.
A two-phase pipeline
Do not render every page. Fetch with plain HTTP first, and render only pages that fail the check.
This keeps the rendering budget for the small share of pages that need it. It also means the rendered path must feed the same normalization, deduplication, and frontier code as the plain path. Only the source of the HTML changes.
Rendering with Playwright
Playwright is a library that drives Chromium, Firefox, or WebKit. Install it with pip install playwright, then download a browser with playwright install chromium.
from playwright.sync_api import sync_playwright
AGENT = 'MyCrawler'
def block_heavy(route):
if route.request.resource_type in ('image', 'font', 'media'):
route.abort()
else:
route.continue_()
class Renderer:
def __init__(self, agent=AGENT):
self._pw = sync_playwright().start()
self._browser = self._pw.chromium.launch()
self._agent = agent
def render(self, url, timeout_ms=15000):
context = self._browser.new_context(user_agent=self._agent)
try:
page = context.new_page()
page.route('**/*', block_heavy)
page.goto(url, wait_until='networkidle', timeout=timeout_ms)
return page.content()
finally:
context.close()
def close(self):
self._browser.close()
self._pw.stop()
renderer = Renderer()
try:
html = renderer.render('https://example.com/')
print(len(html))
finally:
renderer.close()Several choices in this code matter:
- One browser, many contexts. Launching a browser takes a second or more. A context is a cheap, isolated session with its own cookies. Create one per page so that state does not leak between pages, and close it so memory is released.
- Blocking images, fonts, and media. These add load time and bandwidth, and a link extractor does not need them.
- A hard timeout.
gotoraisesplaywright.sync_api.TimeoutError(a subclass ofplaywright.sync_api.Error) when the page does not settle. Catch it in the crawl loop and treat it like any other fetch failure, with the same retry rules. - Returning
page.content(). This is the serialized DOM after scripts ran, so you can pass it straight toLinkExtractor.
Edge cases and failure modes
When is the page "done"? wait_until='networkidle' waits until there has been no network activity for about half a second. Pages with analytics beacons, websockets, or polling may never go idle, and you hit the timeout. The alternative is to wait for a specific element with page.wait_for_selector(...). That is more reliable but needs per-site knowledge. A common compromise is wait_until='load' with a short extra delay and a hard cap.
Links without hrefs. Many SPAs navigate through click handlers or router calls, not anchor tags. A DOM-based LinkExtractor finds only real <a href> elements. Clicking every element to discover routes is slow and can trigger actions such as "delete" or "log out", so most crawlers do not do it.
Fragment routing. Older SPAs use URLs like https://site.example/#/products/7. The normalize function from the normalization chapter drops fragments, which collapses every route of such a site into one URL. For sites that use fragment routing, you must keep the fragment, and the rest of the crawler must treat it as part of the identity.
Infinite scroll. Content loads as the user scrolls. You can scroll in a loop until the page height stops growing, but you need a cap on iterations. Otherwise one feed page can consume the whole budget. This is also a crawl trap with a different cause.
Politeness still applies, and gets harder. Rendering one page makes many requests: the document, scripts, and API calls, sometimes to other hosts. The per-host delay in your frontier governs only the first request. A page that triggers 60 requests in a second is not polite. Limit concurrent renders per host, block unneeded resources, and respect robots.txt for the page itself.
Resource cost. A browser tab can use hundreds of megabytes. Cap the number of concurrent contexts, restart the browser after a set number of pages because long-lived browsers leak memory, and set a memory limit on the process.
Hostile or broken pages. Scripts can open dialogs, redirect repeatedly, or run forever. The timeout and context isolation contain these. Do not allow downloads or file access.
Duplicate content. Rendered output often includes timestamps, session tokens, or randomized markup, so exact-hash deduplication fails more often than for static pages. Hash only the extracted visible text, or use the near-duplicate methods from the content deduplication chapter.
Decision criteria
- If most of your targets are static or server-rendered, plain fetch plus a detection check handles nearly everything.
- If you crawl a small number of known SPA sites, calling their APIs directly is faster and kinder to their servers.
- If you need broad coverage of unknown sites, use the two-phase pipeline and budget for the browser pool.
Exercise
Your crawler reports that a news site has 1 page and 0 links, although every fetch returned status 200 with content type text/html. Name two inexpensive checks you would run before adding a headless browser, and say what each result would tell you.
Show answer
First, search the raw HTML for embedded data such as a __NEXT_DATA__ or JSON-LD script tag. If it exists, parse that JSON and no rendering is needed. Second, open the browser's network panel for the page and look for the JSON request that supplies the content. If there is a stable endpoint, fetch it directly with plain HTTP. If neither exists, the content is built only by client-side code, and rendering with a headless browser is justified, applied only to pages that fail a text-and-links check.