htmlparser2,無瀏覽器相容層,效能約為 JSDOM 的 8 倍。xmlMode、decodeEntities 等解析選項。npm install cheerio
const cheerio = require('cheerio');
const $ = cheerio.load('Hello world
');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
console.log($.html());
// => Hello there!
// 1. 字串
const $ = cheerio.load(htmlString);
// 2. 選擇器 + context + root
$('ul', '#fruits', htmlString); // 在 root 中找 #fruits,再找 ul
// 3. 解析選項
const $ = cheerio.load(html, {
normalizeWhitespace: true, // 合併空白
xmlMode: true, // 嚴格 XML 模式
decodeEntities: true // 解碼實體
});
| 功能 | Cheerio / jQuery | 備註 |
|---|---|---|
| 選擇器 | $('.class'), $('#id'), $('tag') | 支援大多數 CSS3 選擇器 |
| 屬性 | .attr(name), .attr(name, val), .removeAttr() | |
| 資料屬性 | .data(key), .data(key, val) | 自動解析 data-* |
| HTML/文字 | .html(), .html(str), .text(), .text(str) | |
| 類別 | .addClass(), .removeClass(), .toggleClass(), .hasClass() | |
| 遍歷 | .find(), .children(), .parent(), .siblings(), .next(), .prev() | |
| 操作 | .append(), .prepend(), .after(), .before(), .remove(), .replaceWith() | |
| 迭代 | .each(fn), .map(fn) | fn(index, element) |
| 序列化 | .serializeArray() (表單) | 輸出物件陣列 |
| 輸出 | .html() (outer), $.html() (整份文件) |
const axios = require('axios');
const cheerio = require('cheerio');
async function fetchTitles(url) {
const { data: html } = await axios.get(url);
const $ = cheerio.load(html);
const items = [];
$('article h2 a').each((i, el) => {
items.push({ title: $(el).text().trim(), link: $(el).attr('href') });
});
return items;
}
window、document、navigator 等瀏覽器環境模擬。Cheerio 是 Node.js 端「像 jQuery 一樣操作 HTML」的最佳選擇:快、輕、API 熟悉。爬蟲、模板預渲染、HTML 清洗、靜態站點生成等場景皆適合。需執行 JS 時再上 JSDOM 或 Playwright/Puppeteer。