Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Handling JavaScript Rendered Pages in a Web to Markdown Pipeline

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

When you build a web-to-markdown pipeline, you'll quickly hit pages that render content with JavaScript. A simple HTTP request returns only the empty HTML shell, missing the actual text you need. This guide walks you through a robust approach that combines a headless browser with a markdown converter, so your pipeline can handle modern, dynamic sites reliably.

What You'll Need

  • A Node.js environment (v14 or later) – we'll use JavaScript for the examples, but the concepts apply to any language.
  • Basic familiarity with command-line tools and npm.
  • An existing web-to-markdown pipeline, or the willingness to create one from scratch.

Step-by-Step

  1. Choose a headless browser. The most common options are Puppeteer (Chrome) and Playwright (Chromium, Firefox, WebKit). For this guide, we'll use Puppeteer because it's widely adopted and well-documented. Install it in your project:
  2. npm install puppeteer
  3. Create a script that launches the browser and navigates to the target URL. Use puppeteer.launch() to start a headless browser instance, then open a new page with browser.newPage().
  4. Set a realistic viewport and user agent. Some sites serve different content to bots. Set a common viewport (e.g., 1366x768) and a standard user agent string to avoid being blocked or served a stripped-down version.
  5. Navigate to the page and wait for the content to load. Use page.goto(url, { waitUntil: 'networkidle0' }) to ensure all network requests have finished. For pages that load content lazily (e.g., infinite scroll), you may need to scroll or wait for specific selectors. Example: await page.waitForSelector('article').
  6. Extract the rendered HTML. Once the content is loaded, get the full HTML with page.content(). This HTML includes any DOM modifications made by JavaScript.
  7. Convert the HTML to markdown. Use a library like turndown (Node.js) or html2text (Python). Install and import it, then pass the HTML string. For example:
  8. const TurndownService = require('turndown');
    const turndownService = new TurndownService();
    const markdown = turndownService.turndown(html);
  9. Clean up the markdown. Remove navigation elements, ads, and other boilerplate. You can use CSS selectors to exclude them before conversion (e.g., page.$$eval('nav, .ad, .sidebar', el => el.forEach(e => e.remove()))), or post-process the markdown with regex.
  10. Handle pagination and lazy loading. If the page has “Load More” buttons or infinite scroll, you'll need to automate scrolling and clicking until all content is present. A simple loop that scrolls to the bottom and waits a bit can work.
  11. Save the markdown to a file. Write the result to a .md file with a sensible filename, e.g., derived from the URL slug.
  12. Close the browser. Always call browser.close() after you're done to free resources.

Common Mistakes

  • Not waiting long enough. Using waitUntil: 'load' instead of networkidle0 can miss content loaded via AJAX after the initial page load.
  • Forgetting to remove boilerplate. Converting the entire page includes nav menus, footer links, and ads, which clutter your markdown.
  • Blocking yourself. Some sites detect headless browsers and serve CAPTCHAs or block access. Using a real user agent and viewport helps, but you may need to use a stealth plugin.
  • Memory leaks. Launching a new browser for every URL without closing it can exhaust system resources. Reuse a single browser instance across multiple URLs if possible.
  • Assuming all content is in the initial HTML. Single-page applications (SPAs) often render content only after JavaScript runs; always wait for the DOM to be ready.

Tips

  • Use a timeout. Wrap your navigation in a try-catch with a timeout (e.g., 30 seconds) to avoid hanging on slow or unresponsive pages.
  • Cache the rendered HTML. If you're processing the same URL repeatedly, store the HTML locally to avoid re-rendering.
  • Run headless in production. Use puppeteer.launch({ headless: 'new' }) for better performance and lower resource usage.
  • Test with a sample site. Use a known JavaScript-heavy site (like a React-based blog) to verify your pipeline works before scaling.
  • Handle dynamic content carefully. For pages that load content on scroll, you may need to simulate scrolling until the bottom of the page is reached.

Troubleshooting

  • Page loads but content is missing. Increase the wait time or wait for a specific selector that indicates content is ready. Use page.waitForSelector() with a timeout.
  • Browser crashes or times out. Check if the site is blocking headless browsers. Try using a non-headless mode (with a virtual display) or a stealth plugin like puppeteer-extra-plugin-stealth.
  • Markdown is full of junk. Improve your selector-based cleanup. Inspect the page structure and remove elements that don't contain article content.
  • Infinite scroll never ends. Set a maximum number of scrolls to prevent an endless loop.
  • Encoding issues. Ensure you're saving the markdown as UTF-8 to handle special characters correctly.

Frequently Asked Questions

Can I use a simple HTTP request instead of a headless browser?

Only if the page's content is server-rendered. For JavaScript-rendered pages, you need a browser to execute the scripts.

Is Puppeteer the only option?

No. Playwright is a strong alternative, and Selenium works too. Choose based on your language and ecosystem.

How do I handle pages that require login?

You can use Puppeteer to programmatically log in first, then navigate to the target page while maintaining the session.

What if the site uses anti-bot measures?

Use a stealth plugin, rotate user agents, and add delays between requests. Respect the site's terms of service and robots.txt.

Can I convert the HTML to markdown without a library?

You could write your own parser, but it's error-prone. Libraries like Turndown handle edge cases well.

How do I ensure the markdown is clean?

Combine pre-conversion DOM removal with post-processing regex to strip unwanted patterns like excessive whitespace or leftover HTML tags.