萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js 使用 Cheerio 以 jQuery 風格選擇器操作後端 HTML/DOM

為什麼選 Cheerio?

  • 語法熟悉:實作 jQuery 核心 API 子集($、選擇器、DOM 操作、遍歷),學習成本極低。
  • 極速:基於 htmlparser2,無瀏覽器相容層,效能約為 JSDOM 的 8 倍。
  • 輕量:無需完整 DOM 實作、無 JS 執行環境,專注解析與操作 HTML/XML 字串。
  • 彈性:支援 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!

載入 HTML 方式

// 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       // 解碼實體
});

核心 API 對照 jQuery

功能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;
}

何時仍需 JSDOM?

  • 需要**執行**頁面內的 JavaScript(如 SPA 渲染、事件觸發)。
  • 需要完整的 window、document、navigator 等瀏覽器環境模擬。
  • 端到端測試、單元測試模擬 DOM 行為。

總結

Cheerio 是 Node.js 端「像 jQuery 一樣操作 HTML」的最佳選擇:快、輕、API 熟悉。爬蟲、模板預渲染、HTML 清洗、靜態站點生成等場景皆適合。需執行 JS 時再上 JSDOM 或 Playwright/Puppeteer。

copyright © 萬盛學電腦網 all rights reserved