Parsing HTML in JavaScript (Node.js): A Complete Guide
Parsing HTML is one of the key tasks when developing parsers (web scrapers) and automating data collection. In the Node.js ecosystem, there are several powerful libraries that allow you to extract information from HTML documents. In this article, we will break down three main tools: Cheerio, JSDOM, and Puppeteer, compare their capabilities, and provide practical code examples.
1. Cheerio — Lightweight jQuery for the Server
Cheerio is the most popular library for parsing HTML in Node.js. It implements jQuery syntax but works without a browser environment, making it fast and memory-efficient. Cheerio is great for static HTML pages where JavaScript execution is not required.
Installation
npm install cheerioUsage Example
const cheerio = require('cheerio');const axios = require('axios');
async function parsePage(url) { const response = await axios.get(url); const $ = cheerio.load(response.data);
// Extract the page title const title = $('h1').text().trim();
// Collect all links const links = []; $('a').each((i, el) => { const href = $(el).attr('href'); if (href) links.push(href); });
return { title, links };}
// UsageparsePage('https://example.com').then(data => console.log(data));When to choose Cheerio:
- Static pages without dynamic content
- High performance requirements
- Simple jQuery syntax
- No need for JavaScript rendering
2. JSDOM — Full DOM Implementation
JSDOM emulates a browser environment by creating a full DOM model. Unlike Cheerio, JSDOM supports JavaScript execution, allowing you to parse pages whose content is generated by scripts. However, this comes at a cost in functionality — the library consumes more resources.
Installation
npm install jsdomUsage Example
const { JSDOM } = require('jsdom');
async function parseDynamicPage(html) { const dom = new JSDOM(html, { runScripts: 'dangerously', resources: 'usable' });
const document = dom.window.document;
// Wait for scripts to execute await new Promise(resolve => setTimeout(resolve, 2000));
const items = []; document.querySelectorAll('.product-item').forEach(el => { items.push({ name: el.querySelector('.product-name')?.textContent, price: el.querySelector('.price')?.textContent }); });
return items;}
// Example with passing HTMLconst html = `<html><body><div class="product-item">...</div></body></html>`;parseDynamicPage(html).then(data => console.log(data));When to choose JSDOM:
- Pages with dynamic content (AJAX, React, Vue)
- Need to work with DOM events
- Testing web applications
- Extracting data from SPAs (Single Page Applications)
3. Puppeteer — Browser Controlled by Code
Puppeteer is a full headless browser (Chrome/Chromium) with programmatic control. It executes JavaScript, loads resources, and handles cookies and sessions. Puppeteer is the most powerful tool, but also the most resource-intensive.
Installation
npm install puppeteerUsage Example
const puppeteer = require('puppeteer');
async function parseWithBrowser(url) { const browser = await puppeteer.launch({ headless: true }); const page = a