Cheerio is the right tool when the data you need is already present in a page’s HTML response. In Node.js, fetch the response, pass its HTML (or bytes) to Cheerio, select elements with CSS or jQuery-style selectors, and read text or attributes. Cheerio parses markup; it does not open a browser, run JavaScript, click controls, or wait for client-rendered content. If the initial response is only an application shell, use a browser automation tool such as Puppeteer or Playwright instead.
This guide shows the complete workflow, explains every loading method, covers parser and encoding choices, and gives fixes for the failures developers see most often. The Cheerio npm listing showed version 1.2.0 and the introductory documentation stated Node.js 22.19 or later on 2026-09-29; both values can change, so verify them before installing.
What Cheerio can—and cannot—scrape
Cheerio implements a fast, server-side HTML/XML parser with a jQuery-like traversal and manipulation API. It works on the markup supplied to it. It does not render a page or execute its scripts—the official documentation summarizes this as “Cheerio is not a web browser.”
- Good fit: server-rendered articles, product listings, tables, metadata, RSS/XML, and any other values present in the HTTP response.
- Wrong fit: content inserted after load by React, Vue, Angular, or another client-side script; infinite-scroll results that require interaction; login flows, clicks, and pages protected by browser challenges.
The first decision in a scraping project is therefore not which selector to write. It is whether the desired data exists in the response body. Save or inspect the raw response before debugging selectors. If the value is absent there, changing CSS selectors cannot make Cheerio discover it.
#1 Best Overall
- 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.
Set up a Node.js project
The official installation command is:
npm install cheerio
Use the Node.js version required by the current Cheerio documentation (recorded as 22.19 or later on 2026-09-29). A minimal ES-module script can import Cheerio and Node’s built-in fetch:
import * as cheerio from 'cheerio';
const response = await fetch('https://example.com');
if (!response.ok) {
throw new Error(`HTTP ${response.status} for ${response.url}`);
}
const html = await response.text();
const $ = cheerio.load(html);
console.log($('h1').first().text().trim());
Set "type": "module" in package.json, or use the import style supported by your project’s module configuration.
How do I scrape a website with Cheerio?
- Obtain the HTML. Fetch it yourself, read a file, or use one of Cheerio’s loaders.
- Load it. Call
cheerio.loadfor a string, or choose a byte/stream loader when encoding or response size requires it. - Inspect the structure. Confirm the selector against the actual response HTML, not just the browser’s post-JavaScript DOM.
- Select and extract. Use CSS selectors, traversal methods,
.text(),.attr(), and.html(). - Validate. Check selection counts and required fields, then handle missing or malformed values explicitly.
Complete list extraction example
import * as cheerio from 'cheerio';
const url = 'https://example.com/news';
const response = await fetch(url, {
headers: { 'User-Agent': 'my-scraper/1.0' }
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const html = await response.text();
const $ = cheerio.load(html);
const articles = [];
$('article.card').each((index, element) => {
const title = $(element).find('h2').text().trim();
const href = $(element).find('a').attr('href');
const summary = $(element).find('.summary').text().trim();
if (title && href) {
articles.push({
title,
url: new URL(href, url).href,
summary
});
}
});
console.log(JSON.stringify(articles, null, 2));
.text() combines descendant text, while .attr('href') returns an attribute value (or undefined when it is missing). Normalize whitespace and resolve relative links against the page URL. An empty selection normally returns an empty string or undefined, not an exception, so test the selection before treating an extraction as successful.
Choose the loader that matches your input
| Method | Input | Use it when |
|---|---|---|
load |
Decoded string | You already have HTML text. |
loadBuffer |
Node.js Buffer |
Encoding is uncertain and you want byte sniffing. |
stringStream |
Decoded text stream | You receive text incrementally and have already decoded it. |
decodeStream |
Raw byte stream | You need streaming plus encoding detection. |
fromURL |
URL | You want Cheerio to perform the HTTP request. |
String input with load
const $ = cheerio.load('<ul><li>One</li></ul>');
console.log($('li').first().text());
This is the simplest and most explicit approach: your HTTP client controls timeouts, retries, authentication, and response validation; Cheerio only parses the resulting string.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Bytes and streams
loadBuffer(buffer) accepts a Buffer and sniffs its encoding. stringStream parses decoded text as it arrives, while decodeStream accepts raw bytes and performs encoding detection. The stream and URL methods rely on Node.js APIs and are not included in Cheerio’s browser build. Prefer byte-aware methods when a site’s declared charset is unreliable or non-UTF-8.
Loading a URL with fromURL
const $ = await cheerio.fromURL('https://example.com/catalog');
console.log($('title').text().trim());
fromURL is more than a shorthand for fetch followed by load. Current documentation describes these behaviors:
Rank #2
- 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.
- Up to five redirects are followed.
- Non-2xx responses reject with an Undici response error.
- Responses whose content type is not HTML or XML are rejected.
- XML mode is selected from the response content type.
- Encoding comes from a
charsetparameter when present; otherwise bytes are sniffed. - The parser’s
baseURIreflects the final URL after redirects.
When passing requestOptions, include a method explicitly; omitting it causes the call to fail. If you provide headers, your object replaces the default Accept header rather than augmenting it, so include every header you need.
const $ = await cheerio.fromURL('https://example.com/private', {
requestOptions: {
method: 'GET',
headers: {
Accept: 'text/html,application/xhtml+xml',
Authorization: 'Bearer YOUR_TOKEN'
}
}
});
Selectors, traversal, and reliable extraction
Cheerio supports familiar CSS and jQuery-style operations: tags (article), classes (.price), IDs (#main), attributes (a[href]), descendants, child combinators, and methods such as find, first, eq, next, and each.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →const $ = cheerio.load(html);
const heading = $('main h1').first().text().trim();
const canonical = $('link[rel="canonical"]').attr('href');
const prices = $('.price').map((_, el) => $(el).text().trim()).get();
const markup = $('main').html();
if ($('main').length === 0) {
throw new Error('Expected main element was not found in response HTML');
}
Prefer stable attributes and semantic containers over deeply nested positional selectors. Keep extraction functions small, return structured objects, and record the source URL so a failed value can be reproduced. For optional fields, use explicit defaults; for required fields, fail loudly or quarantine the record.
parse5 or htmlparser2?
Cheerio uses parse5 by default for HTML and htmlparser2 by default for XML. Parser choice affects standards fidelity, tolerance of malformed input, speed, and memory.
| Parser | Strength | Trade-off |
|---|---|---|
| parse5 | Browser-standard HTML parsing behavior. | May be less forgiving or heavier for malformed documents. |
| htmlparser2 | Faster, lower-memory, and more tolerant of malformed markup. | Forgiving behavior may not match browser-standard results. |
Use the default for ordinary HTML unless you have a demonstrated compatibility or performance reason to change it. Choose XML mode when the response is XML and preserve the document semantics your downstream code expects.
Can Cheerio scrape a JavaScript-rendered page?
Not by itself. If “view source” or the saved HTTP response contains an empty app shell while the browser later inserts products, comments, or prices, Cheerio has nothing to select. The official troubleshooting guidance points to Puppeteer or Playwright for pages that require rendering; the introduction also names jsdom as a DOM-emulation option.
Rank #3
- 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 before switching tools
- Fetch the URL and save the response body.
- Search that file for a distinctive value visible in the browser.
- Inspect network requests in browser developer tools for a JSON endpoint containing the data.
- If an accessible endpoint exists, request that endpoint directly and parse JSON instead of automating a browser.
- Use Puppeteer or Playwright only when scripts, interaction, session state, or browser APIs are genuinely required.
Browser automation adds startup time, memory use, concurrency limits, and more failure modes. It is not a universal upgrade for static HTML.
Security, limits, and responsible collection
Cheerio parses markup and does not execute scripts, but it is not a sanitizer. Limit input size before parsing to reduce memory pressure. Treat all extracted text and HTML as untrusted. If you later render extracted markup in a browser, sanitize it with a purpose-built sanitizer and apply context-appropriate output encoding. Validate URLs, headers, selectors, and source configuration at your application boundary.
There is no universal legal answer for scraping. Permission depends on the target site, its terms and access controls, jurisdiction, the data involved, and your intended use. Check the site’s policies, respect authentication and technical controls, identify your client where appropriate, rate-limit requests, and obtain qualified advice for consequential projects.
Performance, reliability, and cost decisions
- Fetch once, parse once: reuse the loaded
$object for all fields from a response. - Bound concurrency: a queue prevents memory spikes and avoids overwhelming a target.
- Set timeouts: never let a stalled request occupy a worker indefinitely.
- Cache stable pages: caching reduces load and makes retries cheaper.
- Validate schemas: detect layout changes with required-field checks and selection-count alerts.
- Keep raw evidence: storing the response or a hash helps diagnose parser and selector regressions.
Cheerio itself is an open-source library; your operating costs come from network requests, storage, retries, proxy or browser infrastructure, and engineering time. No durable download statistic or universal throughput benchmark is established here.
Recommended Free Tools
Common errors and fixes
“My selector returns nothing”
Check the saved response, spelling, case, nesting, and whether the browser generated the node after load. Log $.html() or a narrow container and inspect selection.length.
fromURL rejects the response
Check the status code, redirect chain, and Content-Type. Non-2xx responses and non-HTML/XML content types are documented rejection cases. A download, image, or PDF URL is not a valid HTML input.
Rank #4
- 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
Custom request options fail
Include method whenever you pass requestOptions. If you set headers, include the required Accept value because the supplied object replaces the default.
Characters are corrupted
Use loadBuffer or decodeStream so Cheerio can sniff bytes, and check the server’s charset declaration. Avoid converting bytes to UTF-8 before parsing when the original encoding is uncertain.
The parser is slow or memory-heavy
Reduce input size, avoid retaining full documents, process streams where appropriate, and evaluate htmlparser2 when its tolerance and lower-memory behavior fit your markup. Confirm output differences before changing parser configuration.
Untrusted output looks unsafe
Parsing is not sanitization. Keep untrusted values as data, sanitize before browser rendering, and apply an allowlist for any HTML you intentionally preserve.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If your goal is a clean screenshot or PDF rather than structured DOM data, ScreenshotNeo makes one HTTP request to capture a page. It accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
Use the API documentation at https://screenshotneo.com/docs/ for all options, including full-page and element captures, device presets, retina scale, PDF settings, custom CSS/JavaScript, waits, request blocking, headers, cookies, authentication, geolocation, caching, signed links, asynchronous webhooks, bulk capture, and usage data.
Free tools Windows power users keep installed
One-click scans. No signup required.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Sign up for ScreenshotNeo free.
Best Value
- 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.
Frequently Asked Questions
Does Cheerio execute JavaScript?
No. It parses supplied HTML or XML and never runs page scripts. Use a browser automation tool when the required nodes are created client-side.
Which Cheerio loader should I use for unknown encoding?
Use loadBuffer for a complete Buffer or decodeStream for a raw byte stream; both allow encoding detection instead of assuming UTF-8.
Is Cheerio a sanitizer?
No. Limit input size and sanitize untrusted markup before rendering it in a browser.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteWhy does fromURL reject my URL?
Typical documented causes are a non-2xx response, a non-HTML/XML content type, more than five redirects, or invalid requestOptions such as a missing method.
The Bottom Line
Use Cheerio when the target values are in the HTTP response: fetch or load the bytes, parse once, select with stable CSS selectors, and validate every required field. Move to Puppeteer or Playwright only when browser execution or interaction is part of the requirement.
Quick Recap
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.

