Sub topic 15
Pages that need JavaScript to render
This chapter assumes you have read the earlier chapters on fetching pages and extracting links. You should also know that browsers run JavaScript after loading a page.
The problem
The crawler so far downloads HTML and parses it. Many sites ship a nearly empty HTML shell and build the content in the browser with JavaScript. The response body might contain only <div id="app"></div> and a script tag. LinkExtractor finds no anchors, so the crawl stops at that page.
There are three ways to handle this:
- Skip such pages and accept the loss.
- Find the data API the page calls and fetch that directly. This is cheap, but it is specific to each site.
- Render the page in a headless browser, which is a real browser engine with no visible window. It runs the scripts and gives you the final DOM, the page structure after scripts have run.
Detecting when rendering is needed
Rendering is slow and memory-hungry, so use it only when the plain fetch looks empty. A simple heuristic works as a first filter.
from html.parser import HTMLParser
class LinkExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag == 'a':
for name, value in attrs:
if name == 'href' and value:
self.links.append(value)
def looks_unrendered(html):
extractor = LinkExtractor()
extractor.feed(html)
has_script = '<script' in html.lower()
return has_script and not extractor.links
print(looks_unrendered('<div id="app"></div><script src="/app.js"></script>')) # True
print(looks_unrendered('<a href="/about">About</a><script></script>')) # FalseThis heuristic misses pages that have some static links but load the main content with JavaScript. Tune it per crawl, for example by comparing text length before and after rendering on a sample.
Rendering with a headless browser
Playwright is one common tool. Install it with pip install playwright and then playwright install chromium.
from playwright.sync_api import sync_playwright
def render(url, timeout_ms=15000):
with sync_playwright() as p:
browser = p.chromium.launch()
try:
page = browser.new_page(user_agent='MyCrawler')
page.goto(url, wait_until='networkidle', timeout=timeout_ms)
return page.content()
finally:
browser.close()page.content() returns the HTML after scripts have run. You can pass it to LinkExtractor and normalize unchanged. In the crawl loop, call render only when looks_unrendered(html) is true.
Launching a browser per page, as above, is simple but costly. A real crawler keeps a small pool of long-lived browsers and opens a new page in one of them for each URL.
Costs and failure modes
- Cost. Rendering takes seconds and hundreds of megabytes per browser, against milliseconds for a plain fetch. It often cuts throughput by an order of magnitude.
- Politeness. A rendered page triggers many extra requests for scripts, images, and API calls. These hit the host as well, so the per-host delay applies to them too.
- Unbounded pages. Scripts can loop, poll, or load content forever. Always set a timeout and kill the browser when it expires.
- Waiting too little or too much.
networkidlecan return before late content appears, or never return on pages that poll. Waiting for a specific element is more reliable when you know the site. - Links that are not anchors. Click handlers that navigate without an
hrefare invisible to link extraction, even after rendering.
Exercise
A page's raw HTML contains one script tag and no anchors, but your crawler never renders it. Name the cheapest alternative to a headless browser for getting its links, and one drawback of that alternative.
Show answer
Find the JSON API the page's script calls (for example in the browser's network tab) and fetch that endpoint directly, then read the URLs from the JSON. The drawback is that it is specific to each site and breaks when the site changes its API.