Parsing HTML in TypeScript: Choosing a Tool
Parsing HTML is one of the key tasks when developing parsers, web scraping, content analysis, and test automation. In the TypeScript (and Node.js) ecosystem, there are several mature libraries that allow you to work with HTML documents, extract data, modify the DOM, and execute queries. In this article, we will look at three main tools: cheerio, jsdom, and node-html-parser, and also show examples of their use with full typing.
Why Parse HTML in TypeScript?
TypeScript adds strict typing, which is especially useful when working with unstructured data from HTML. You can precisely define the types of extracted fields, avoid runtime errors, and improve code readability. Libraries for parsing HTML in TypeScript usually have built-in types or come with @types/* packages.
1. Cheerio — Lightweight and Fast Parser
Cheerio is a fast, flexible, and lightweight library that implements a subset of jQuery for the server side. It does not create a full DOM, but parses HTML and provides a convenient API for navigation and manipulation.
Installation
npm install cheerionpm install --save-dev @types/cheerioUsage Example with TypeScript
import * as cheerio from 'cheerio';
interface ParsedProduct { title: string; price: number; link: string;}
const html = ` <div class="product"> <h2 class="title">Laptop</h2> <span class="price">75000</span> <a href="/product/1">Details</a> </div>`;
const $ = cheerio.load(html);const products: ParsedProduct[] = [];
$('.product').each((index, element) => { const title = $(element).find('.title').text().trim(); const priceText = $(element).find('.price').text().trim(); const price = parseFloat(priceText); const link = $(element).find('a').attr('href') || '';
if (title && !isNaN(price)) { products.push({ title, price, link }); }});
console.log(products);// [{ title: 'Laptop', price: 75000, link: '/product/1' }]Pros: high performance, familiar jQuery syntax, small size.
Cons: does not support JavaScript execution, no full DOM.
2. JSDOM — Full DOM in Node.js
JSDOM is an implementation of the WHATWG DOM and HTML standards in pure JavaScript for Node.js. It creates a full document, supports scripts, events, and all modern browser APIs.
Installation
npm install jsdomnpm install --save-dev @types/jsdomExample with Typing
import { JSDOM } from 'jsdom';
interface Article { headline: string; summary: string; url: string;}
const html = ` <article> <h1>TypeScript 5.0: New Features</h1> <p>Overview of key changes and improvements</p> <a href="/article/ts5">Read</a> </article>`;
const dom = new JSDOM(html);const document = dom.window.document;
const articles: Article[] = [];const articleElements = document.querySelectorAll('article');
articleElements.forEach((article) => { const headline = article.querySelector('h1')?.textContent?.trim() || ''; const summary = article.querySelector('p')?.textContent?.trim() || ''; const url = article.querySelector('a')?.getAttribute('href') || ''; articles.push({ headline, summary, url });});
console.log(articles);Pros: full browser emulation, JavaScript support, working with forms, events.
Cons: heavier, slower than cheerio, consumes more memory.