Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cheerio is a JavaScript library that parses HTML or XML into a queryable data structure and exposes a fast, jQuery-like API for selecting, reading, and changing nodes. It works on markup your program already has; it does not open a visible browser, apply CSS, load external resources, or execute the page’s JavaScript. That distinction determines whether Cheerio is the right tool for a scraper, feed converter, test utility, or document transformer.

Cheerio in one sentence

The Cheerio project describes its purpose this way: “Cheerio parses markup and provides an API for working with the resulting data structure.” In practice, your code obtains HTML or XML, passes it to Cheerio, uses CSS selectors and jQuery-style traversal methods, and optionally serializes the modified tree back to a string.

Cheerio is therefore closer to a server-side markup processor than to a browser. A browser builds a DOM while also running JavaScript, calculating styles, fetching subresources, and painting pixels. Cheerio concentrates on parsing and manipulating the document tree.

What Cheerio can and cannot do

Task Cheerio Browser automation (such as Puppeteer or Playwright)
Parse HTML or XML already in memory Yes Yes, with more overhead
CSS-style element selection Yes Yes
Read or change text, attributes, and markup Yes Yes
Execute page JavaScript No Yes
Render CSS, images, fonts, or layout No Yes
Wait for client-side content to appear No Yes
Process a response fetched by your own HTTP client Yes Usually, but a browser is not necessary

If a site sends the article body in its initial HTML response, Cheerio can usually extract it. If the initial response is only an application shell and JavaScript later requests and inserts the data, Cheerio alone will not see that browser-created content.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Install Cheerio and load your first document

Install the package in a Node.js project:

npm install cheerio

With ECMAScript modules, import Cheerio and load a string:

import * as cheerio from 'cheerio';

const $ = cheerio.load('<h2 class="title">Hello world</h2>');
const heading = $('h2.title').text();
console.log(heading); // Hello world

console.log($.html());

cheerio.load() returns a function, conventionally named $. Calling $('selector') creates a collection of matching nodes. Methods such as .text(), .attr(), .html(), .find(), .first(), .each(), .filter(), .remove(), and .prepend() provide the familiar jQuery-style workflow.

CommonJS projects can use the equivalent form:

const cheerio = require('cheerio');
const $ = cheerio.load('<p>CommonJS works too</p>');

Extract data with selectors

Suppose a response contains product cards:

import * as cheerio from 'cheerio';

const html = `
  <ul class="products">
    <li class="product" data-id="a17">
      <a class="name" href="/one">One</a>
      <span class="price">$12</span>
    </li>
    <li class="product" data-id="b42">
      <a class="name" href="/two">Two</a>
      <span class="price">$18</span>
    </li>
  </ul>`;

const $ = cheerio.load(html);
const products = [];

$('.product').each((_, element) => {
  const card = $(element);
  products.push({
    id: card.attr('data-id'),
    name: card.find('.name').text().trim(),
    url: card.find('.name').attr('href'),
    price: card.find('.price').text().trim()
  });
});

console.log(products);

Use .text() when you want descendant text combined into one string. Use .html() to obtain the inner markup, and .attr('href') or .prop() when you need an attribute or property. Always trim and normalize values at your application boundary; markup often contains indentation and line breaks.

Transform and serialize markup

Cheerio is also useful for sanitizing or rewriting documents:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import * as cheerio from 'cheerio';

const $ = cheerio.load('<article><h1>Title</h1><script>bad()</script></article>');
$('script, style, .advertisement').remove();
$('h1').attr('data-indexed', 'true');
$('article').prepend('<p class="notice">Updated</p>');

const output = $.html();
console.log(output);

Serialization is performed with $.html(). Remember that serialization reflects Cheerio’s parser and options; it is not a screenshot and does not prove that the result will look identical in a browser.

Loading HTML, XML, bytes, streams, and URLs

The loading guide documents several input paths. Choose based on what your program receives:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
  • load(markup): use when decoded HTML or XML is already a string.
  • loadBuffer(buffer): use for raw bytes when the character encoding is unknown; Cheerio can perform encoding sniffing.
  • stringStream(options, callback): use for a stream of already-decoded text.
  • decodeStream(options, callback): use for a stream of raw bytes and let Cheerio handle encoding detection.
  • fromURL(url): ask Cheerio to retrieve a URL and parse the response. The documented behavior rejects responses whose content type is neither HTML nor XML.

For production fetching, an explicit HTTP client can give you clearer control over redirects, authentication, retry policy, timeouts, and status codes. Pass the response body to load after checking those conditions. Do not assume that a successful TCP request means the page contains the data you need.

HTML parsing versus XML parsing

Cheerio’s parser defaults depend on the markup type. The documentation states that parse5 is the default for HTML. It follows HTML parsing rules and creates a tree intended to match how a browser would construct one, including correction of many malformed structures.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

htmlparser2 is the default for XML. The configuration documentation describes it as faster, lower-memory, and more forgiving of malformed markup, and says it can also be selected for HTML when those characteristics are preferred or parse5’s browser-oriented behavior is not suitable. Those are project documentation descriptions, not a benchmark for your workload.

When parser behavior matters, make the choice explicit and test representative input:

import * as cheerio from 'cheerio';

const browserLike = cheerio.load(markup, { xml: false });
const xmlMode = cheerio.load(markup, { xml: true });

Use XML mode for XML-shaped data where case, self-closing elements, and XML parsing rules matter. Use the default HTML behavior for ordinary web pages unless your input or memory constraints justify another parser configuration.

Why client-rendered pages are a common failure

Cheerio only parses the markup supplied to it. Consider a page whose initial response contains <div id="app"></div>, followed by a script that fetches products and inserts cards. A request followed by cheerio.load(responseBody) sees an empty app container because no JavaScript engine ran.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Diagnose this by inspecting the raw response, not just the browser’s Elements panel. If the desired text is absent from “View Source” or the HTTP response body, Cheerio cannot create it from nothing. Options include:

  • Call the site’s underlying JSON endpoint directly, when you are authorized to do so.
  • Use a browser automation tool such as Puppeteer or Playwright when JavaScript execution, interaction, or authenticated browser state is required.
  • Use jsdom when a DOM-emulation project fits better than a full browser.

Cheerio’s own introduction names Puppeteer and Playwright for browser automation and jsdom for DOM emulation. Select based on whether you need execution and browser behavior or only markup processing.

Cheerio compared with browser-oriented tools

Choose Cheerio when

  • The HTML or XML is already available.
  • You need extraction, filtering, cleanup, conversion, or rewriting.
  • You want a small API surface without a browser process.
  • You do not need CSS layout, image loading, navigation, or client-side JavaScript.

Choose Puppeteer or Playwright when

  • Data appears only after scripts execute.
  • You must click, type, scroll, authenticate, or wait for network activity.
  • You need browser screenshots, PDF rendering, or layout-dependent assertions.

Choose jsdom when

  • You need a DOM-emulation environment for JavaScript tests or browser-like APIs.
  • A full browser is unnecessary, but a plain markup selector API is insufficient.

The key decision is not “which selector library is fastest?” It is whether your task begins with complete markup or requires a browser to produce that markup.

Performance, reliability, and safety considerations

Keep fetching separate from parsing

Cheerio does not define your network timeout, retry, cache, or robots policy. Put those concerns in the HTTP layer, set bounded timeouts, check status and content type, and log the URL and parser outcome. Then parse only the body you intentionally accepted.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Limit input size

Parsing a very large document consumes memory. Enforce response-size limits before buffering untrusted input, and prefer stream loading when your pipeline naturally receives streams. Remove nodes you do not need before retaining large serialized output.

Treat extracted text as untrusted

Cheerio can read and write markup; it is not an HTML security policy. Escape or sanitize output according to where it will be displayed, especially when inserting extracted values into another HTML page, template, email, or database-backed editor.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Make selectors resilient

Prefer stable attributes or semantic structure over deeply nested positional selectors. Check for missing nodes and attributes, and write tests against fixtures that represent redesigns, missing fields, and malformed markup.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting checklist

“My selector returns zero elements”

  • Print a short prefix of the raw response and verify the expected element is actually present.
  • Check whether the selector targets the response’s structure rather than a browser-generated DOM.
  • Confirm class names, casing, and escaping; then test a simpler selector such as body or the element’s tag.

“The text is empty, but I can see it in Chrome”

The content is probably inserted by client-side JavaScript or fetched after load. Inspect the original response and use an API request or browser automation instead of expecting Cheerio to execute scripts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“The parsed tree differs from the source”

HTML parsers repair malformed markup. Compare parse5’s browser-oriented behavior with htmlparser2 when appropriate, and add a fixture test for the exact structure your application depends on.

“fromURL refuses the response”

Check the server’s Content-Type. The documented fromURL route refuses content types that are neither HTML nor XML. Fetch the resource yourself if it is an API response or if you need custom validation.

“Characters are garbled”

Use loadBuffer or decodeStream for raw bytes when encoding is uncertain. Passing incorrectly decoded text to load cannot recover the original characters.

When you need a screenshot instead of a parsed tree

Cheerio cannot render a page or produce a visual capture. If your requirement is a clean website screenshot, ScreenshotNeo provides a screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed, while bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, with the result identified by X-Page-Verdict and X-Billed headers.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an API call, see the ScreenshotNeo documentation:

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

It also supports full-page and element captures, device presets, custom viewports, retina scale, PDF output, custom CSS and JavaScript, clicks, waits, blocking rules, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed links, asynchronous webhooks, bulk capture, usage reporting, and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Plans include 1,000 free shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.

Frequently asked questions

Is Cheerio a browser?

No. It parses supplied markup but does not provide visual rendering, CSS layout, external-resource loading, or page JavaScript execution.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can Cheerio scrape a website?

Yes, when the needed data is present in HTML or XML that your program can obtain. For JavaScript-generated data, use the site’s permitted data endpoint or a browser-capable tool.

Does Cheerio support XML?

Yes. XML loading is supported, with htmlparser2 documented as the default parser for XML.

Does Cheerio replace jQuery?

It provides a similar selection and manipulation style for server-side markup, but it is not a browser-installed jQuery runtime and does not reproduce browser behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.