cheerio

Cheerio is a Node.js library for loading and querying HTML or XML with a jQuery-like API. Give it markup, then use familiar selectors such as $('h1') or $('.price') to read or traverse elements. It is a parser, not a browser.

A Small Example

import * as cheerio from 'cheerio';

const $ = cheerio.load('<h1 class="title">Books</h1>');
const title = $('.title').text();

The $ function searches the parsed document. Cheerio does not fetch the HTML for you in every setup; commonly, a separate HTTP client gets the response and passes its body to cheerio.load().

When Cheerio Is a Good Fit

It works well when the response already contains the content you need and CSS selectors are a convenient way to extract it. It is lighter than launching a full browser for every page. If a site inserts the target content with JavaScript, Cheerio will not run those scripts; inspect the received HTML first, then use a browser-based tool only if rendering is actually required.

One easy trap: an empty selection often returns an empty string rather than throwing an error. Check the number of matches before assuming your selector found the right field. Also trim or normalize whitespace yourself when the source markup contains line breaks and indentation.

Sources

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *