DE EN ES FR ID JA KO PT RU TH VI ZH

Cheerio v1.2.0 文档

Cheerio 是一个快速、灵活且优雅的库,用于在服务器端解析和操作 HTML 和 XML。它实现了 jQuery 核心功能的一个子集,为开发者提供了熟悉的 API,同时针对服务器端环境进行了优化。

当前版本 (1.2.0) 功能特性

核心加载方法

当前版本提供了几种强大的方式来加载和解析 HTML/XML 文档:

import * as cheerio from 'cheerio';

// Basic loading from string
const $ = cheerio.load('<h2 class="title">Hello world</h2>');

// Loading from buffer with encoding detection
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);

// Loading from URL with automatic encoding detection
const $ = await cheerio.fromURL('https://example.com');

// Stream-based loading for large documents
const stream = cheerio.stringStream({}, (err, $) => {
  if (!err) {
    console.log($('h1').text());
  }
});

增强的 TypeScript 支持

版本 1.2.0 包含了全面的 TypeScript 定义,提升了类型安全性:

import { CheerioAPI, Cheerio, Element } from 'cheerio';

// Strongly typed element selection
const $: CheerioAPI = cheerio.load(html);
const elements: Cheerio<Element> = $('.my-class');

新的 Extract API

用于从 HTML 文档中提取数据的强大新功能:

const data = $root.extract({
  title: 'h1',
  links: [{ selector: 'a', value: 'href' }],
  metadata: {
    selector: '.meta',
    value: {
      author: '.author',
      date: '.date'
    }
  }
});

高级 URL 处理

通过 baseURI 增强了 URL 解析支持:

const $ = cheerio.load(html, { 
  baseURI: 'https://example.com/page/' 
});

// Automatically resolves relative URLs
$('a').prop('href'); // Returns absolute URL
$('img').prop('src'); // Returns absolute URL

按类别划分的主要功能

DOM 操作

表单处理

// Serialize forms to URL-encoded strings
$('form').serialize(); // 'name=value&email=test@example.com'

// Get form data as structured arrays
$('form').serializeArray();
// [{ name: 'username', value: 'john' }, ...]

CSS 和样式

// Get/set CSS properties
$('.element').css('color', 'red');
$('.element').css(['margin', 'padding']); // Get multiple properties

// Class manipulation
$('.item').addClass('active selected');
$('.item').removeClass('old-class');
$('.item').toggleClass('visible');

数据属性

// HTML5 data-* attribute support with automatic type coercion
$('.widget').data('config'); // Parses JSON automatically
$('.widget').data('count', 42); // Set data programmatically

从旧版本迁移

从 0.x 到 1.x

需要注意的关键变更

// Old way (0.x) - still works but discouraged
const cheerio = require('cheerio');
const $ = cheerio.load(html);

// New way (1.x) - recommended
import * as cheerio from 'cheerio';
const $ = cheerio.load(html);

性能改进

版本 1.2.0 包含了显著的性能增强:

// Stream processing for large files
const stream = cheerio.decodeStream({
  encoding: { defaultEncoding: 'utf8' }
}, (err, $) => {
  // Process document as it streams
});

高级功能

自定义解析器选项

const $ = cheerio.load(html, {
  xmlMode: true,        // Parse as XML
  decodeEntities: false, // Don't decode HTML entities
  scriptingEnabled: false // Disable script tag processing
});

带选项的网络加载

const $ = await cheerio.fromURL('https://api.example.com/data', {
  requestOptions: {
    headers: { 'User-Agent': 'MyBot/1.0' }
  },
  encoding: { defaultEncoding: 'utf8' }
});

最佳实践

  1. 使用 TypeScript:充分利用全面的类型定义
  2. 流式处理大型文档:使用流 API 获得更好的内存管理
  3. 利用 extract API:使用新的 extract 方法进行结构化数据提取
  4. 设置 baseURI:在爬取网站时,设置 baseURI 以正确解析 URL

浏览器与服务器端的差异

Cheerio 专为服务器端使用而设计,移除了特定于浏览器的 jQuery 功能,同时添加了针对服务器优化的功能,例如:

这使得 Cheerio 非常适合在 Node.js 环境中进行网页抓取、服务器端渲染以及任何 HTML/XML 处理任务。