安装
Cheerio 是专为 Node.js 环境设计的服务器端核心 jQuery 实现。本指南涵盖了在项目中安装和配置 Cheerio 的所有方法。
Package Manager 安装
npm
npm install cheerio
yarn
yarn add cheerio
pnpm
pnpm add cheerio
bun
bun add cheerio
导入语法
ESM (ES Modules) - 推荐
import * as cheerio from 'cheerio';
// Load HTML and create a Cheerio instance
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
// Manipulate elements
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
console.log($.html());
// => <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
CommonJS
const cheerio = require('cheerio');
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
解构导入
// Import specific functions
import { load, contains, merge } from 'cheerio';
const $ = load('<ul><li>Apple</li><li>Orange</li></ul>');
TypeScript 配置
Cheerio 内置了 TypeScript 类型定义,无需额外安装 @types package。
基本 TypeScript 用法
import * as cheerio from 'cheerio';
import type { CheerioAPI, Element } from 'cheerio';
const html = '<div class="container"><p>Hello</p></div>';
const $: CheerioAPI = cheerio.load(html);
// Type-safe element selection
const elements: cheerio.Cheerio<Element> = $('.container p');
const text: string | undefined = elements.text();
高级类型用法
import type { AnyNode, CheerioOptions } from 'cheerio';
const options: CheerioOptions = {
xmlMode: true,
decodeEntities: false
};
const $ = cheerio.load('<xml><item>data</item></xml>', options);
环境支持
Node.js 要求
- 最低 Node.js 版本: 18.17 或更高
- 推荐: Node.js 20+ 以获得最佳性能
- Cheerio 专为服务器端使用而设计
浏览器限制
⚠️ 重要: Cheerio 不是为浏览器环境设计的。它是一个服务器端库,具有以下特点:
- 使用 Node.js 特定的 API
- 不包含 jQuery 提供的 DOM 不一致性处理
- 针对服务器端 HTML 解析和操作进行了优化
在浏览器环境中,请使用 jQuery 或现代 DOM API。
高级加载方法
从 Buffer 加载
import * as cheerio from 'cheerio';
import * as fs from 'fs';
// Load from buffer with encoding detection
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);
从 URL 加载
import * as cheerio from 'cheerio';
// Fetch and parse HTML from a URL
const $ = await cheerio.fromURL('https://example.com');
console.log($('title').text());
流式 HTML 处理
import * as cheerio from 'cheerio';
import * as fs from 'fs';
// Parse HTML streams
const writeStream = cheerio.stringStream({}, (err, $) => {
if (err) {
console.error('Parse error:', err);
return;
}
console.log($('h1').text());
});
fs.createReadStream('document.html', { encoding: 'utf8' })
.pipe(writeStream);
配置选项
解析器选项
import * as cheerio from 'cheerio';
const $ = cheerio.load(html, {
// Use XML mode for XML documents
xmlMode: false,
// Decode HTML entities
decodeEntities: true,
// Set base URI for resolving relative URLs
baseURI: 'https://example.com',
// Enable/disable scripting
scriptingEnabled: false
});
常见安装问题
Node.js 版本冲突
错误: Cannot find module 'cheerio' 或兼容性警告
解决方案: 确保使用 Node.js 18.17 或更高版本:
node --version
# Should show v18.17.0 or higher
# Update Node.js if needed
npm install -g n # For Unix systems
n latest
ESM/CommonJS Module 问题
错误: require() of ES Module 或在 CommonJS 中使用 import 语句
解决方案: 确保 package.json 具有正确的 module 类型:
{
"type": "module"
}
或为您的环境使用适当的导入语法。
TypeScript 配置
错误: Cheerio 类型的 TypeScript 编译错误
解决方案: 更新您的 tsconfig.json:
{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true
}
}
大文档的内存问题
错误: JavaScript heap out of memory
解决方案: 增加 Node.js 内存限制:
node --max-old-space-size=4096 your-script.js
或使用流式方法以较小的块处理文档。
编码问题
错误: 解析的 HTML 中字符编码不正确
解决方案: 使用带有显式编码选项的 loadBuffer():
const $ = cheerio.loadBuffer(buffer, {
encoding: {
defaultEncoding: 'utf8'
}
});
验证
验证您的安装是否正常工作:
import * as cheerio from 'cheerio';
const $ = cheerio.load('<h1>Test</h1>');
console.log($('h1').text()); // Should output: "Test"
// Check version
console.log('Cheerio version:', cheerio.version || 'Version info not available');
通过这些安装步骤,您就可以开始在 Node.js 应用程序中使用 Cheerio 强大的类 jQuery API 来解析和操作 HTML 了。