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

Cheerio API 参考

Cheerio 是一个快速、灵活且优雅的服务器端 jQuery 核心功能实现。它为在 Node.js 环境中解析和操作 HTML 和 XML 文档提供了熟悉的类 jQuery API。

核心加载函数

cheerio.load(content, options?)

加载 HTML/XML 内容并返回一个用于查询和操作的 CheerioAPI 实例。

函数签名:

function load(
  content: string | AnyNode | AnyNode[] | Buffer,
  options?: CheerioOptions,
  isDocument?: boolean
): CheerioAPI

参数:

名称 类型 默认值 描述
content string | AnyNode | AnyNode[] | Buffer - 要解析的 HTML/XML 内容
options CheerioOptions {} 解析器和行为选项
isDocument boolean true 是否将内容视为完整文档

返回值: CheerioAPI - 具有类 jQuery 方法的 Cheerio 实例

示例:

import * as cheerio from 'cheerio';

// Basic HTML loading
const $ = cheerio.load('<ul><li>Apple</li><li>Orange</li></ul>');

// With options
const $ = cheerio.load('<xml><item>data</item></xml>', {
  xmlMode: true,
  decodeEntities: false
});

// Loading from buffer
const buffer = Buffer.from('<div>Hello</div>');
const $ = cheerio.load(buffer);

常见陷阱:

元素选择

$(selector, context?, root?)

使用 CSS 选择器从已加载的文档中选择元素,类似于 jQuery 的 $() 函数。

函数签名:

function $(
  selector: string | AnyNode | AnyNode[] | Cheerio<AnyNode>,
  context?: string | AnyNode | Cheerio<AnyNode>,
  root?: string | Document
): Cheerio<Element>

参数:

名称 类型 默认值 描述
selector string | AnyNode | AnyNode[] | Cheerio<AnyNode> - CSS 选择器或要选择的元素
context string | AnyNode | Cheerio<AnyNode> document 搜索的上下文范围
root string | Document - 上下文的根文档

返回值: Cheerio<Element> - 匹配元素的集合

示例:

// Basic selection
$('li').length; // Number of <li> elements
$('.apple').text(); // Text content of first element with class 'apple'

// With context
$('li', '#fruits').addClass('fruit'); // Find <li> within #fruits

// Complex selectors
$('li:nth-child(2n)').css('color', 'red'); // Every other <li>
$('a[href^="https://"]').attr('target', '_blank'); // External links

属性操作

.attr(name, value?)

获取或设置匹配元素的属性。

函数签名:

// Get attribute
function attr(name: string): string | undefined;
// Set attribute
function attr(name: string, value: string | null | ((i: number, attr: string) => string | null)): Cheerio<T>;
// Set multiple attributes
function attr(attributes: Record<string, string | null>): Cheerio<T>;

参数:

名称 类型 默认值 描述
name string | Record<string, string | null> - 属性名或对象映射
value string | null | function - 要设置的值、删除用 null 或函数

返回值: string \| undefined \| Cheerio<T> - 属性值(getter)或 Cheerio 实例(setter)

示例:

// Get attribute
const href = $('a').attr('href'); // Gets href of first <a>

// Set attribute
$('img').attr('alt', 'Description'); // Sets alt text
$('a').attr('href', null); // Removes href attribute

// Multiple attributes
$('input').attr({
  type: 'text',
  placeholder: 'Enter name',
  required: 'required'
});

// Function-based setting
$('img').attr('src', (i, src) => src.replace('http://', 'https://'));

常见陷阱:

.prop(name, value?)

获取或设置 DOM 元素的属性,处理特殊属性如 checkedselected 等。

函数签名:

// Get property
function prop(name: string): any;
// Set property
function prop(name: string, value: any): Cheerio<T>;
// Set multiple properties
function prop(properties: Record<string, any>): Cheerio<T>;

参数:

名称 类型 默认值 描述
name string | Record<string, any> - 属性名或对象映射
value any - 要设置的值

返回值: any \| Cheerio<T> - 属性值(getter)或 Cheerio 实例(setter)

示例:

// Get property
const isChecked = $('input[type="checkbox"]').prop('checked'); // true/false

// Set property
$('input[type="checkbox"]').prop('checked', true);
$('option').prop('selected', false);

// Special properties
$('a').prop('href'); // Resolved absolute URL
$('div').prop('outerHTML'); // Full HTML including the element
$('div').prop('innerHTML'); // Inner HTML content

.data(key, value?)

获取或设置数据属性,对 HTML5 data-* 属性进行自动类型转换。

函数签名:

// Get all data
function data(): Record<string, unknown>;
// Get specific data
function data(key: string): unknown;
// Set data
function data(key: string, value: unknown): Cheerio<T>;
// Set multiple data
function data(values: Record<string, unknown>): Cheerio<T>;

参数:

名称 类型 默认值 描述
key string | Record<string, unknown> - 数据键或对象映射
value unknown - 要设置的值

返回值: unknown \| Record<string, unknown> \| Cheerio<T> - 数据值或 Cheerio 实例

示例:

// HTML: <div data-user-id="123" data-active="true">
const userId = $('.user').data('userId'); // 123 (number)
const isActive = $('.user').data('active'); // true (boolean)

// Set data
$('.user').data('lastSeen', new Date());
$('.user').data({
  role: 'admin',
  permissions: ['read', 'write']
});

// Camel case conversion
$('<div data-foo-bar="test">').data('fooBar'); // "test"

常见陷阱:

内容操作

.text(value?)

获取或设置元素的文本内容,去除所有 HTML 标签。

函数签名:

// Get text
function text(): string;
// Set text
function text(value: string | number | ((i: number, text: string) => string | number)): Cheerio<T>;

参数:

名称 类型 默认值 描述
value string | number | function - 要设置的文本内容或函数

返回值: string \| Cheerio<T> - 文本内容(getter)或 Cheerio 实例(setter)

示例:

// Get text content
const title = $('h1').text(); // "Welcome to My Site"

// Set text (HTML-safe)
$('h1').text('New <Title>'); // Displays: "New <Title>" (not rendered as HTML)

// Function-based setting
$('li').text((i, currentText) => `${i + 1}. ${currentText}`);

.html(value?)

获取或设置元素的内部 HTML 内容。

函数签名:

// Get HTML
function html(): string | null;
// Set HTML
function html(value: string | ((i: number, html: string) => string)): Cheerio<T>;

参数:

名称 类型 默认值 描述
value string | function - 要设置的 HTML 内容或函数

返回值: string \| null \| Cheerio<T> - HTML 内容(getter)或 Cheerio 实例(setter)

示例:

// Get HTML
const content = $('.container').html(); // "<p>Hello <strong>world</strong></p>"

// Set HTML
$('.container').html('<p>New content</p>');

// Function-based setting
$('div').html((i, oldHtml) => `<span>Item ${i}</span>${oldHtml}`);

常见陷阱:

.val(value?)

获取或设置表单元素(input、select、textarea)的值。

函数签名:

// Get value
function val(): string | string[] | undefined;
// Set value
function val(value: string | string[]): Cheerio<T>;

参数:

名称 类型 默认值 描述
value string | string[] - 要设置的值(多选用数组)

返回值: string \| string[] \| undefined \| Cheerio<T> - 表单值或 Cheerio 实例

示例:

// Get values
const inputValue = $('input[name="email"]').val(); // "user@example.com"
const selectedOptions = $('select[multiple]').val(); // ["option1", "option2"]

// Set values
$('input[type="text"]').val('New value');
$('select[multiple]').val(['option1', 'option3']); // Selects multiple options
$('textarea').val('Long text content...');

DOM 操作

.append(content)

将内容作为每个匹配元素的最后一个子元素插入。

函数签名:

function append(
  ...contents: (
    | string
    | AnyNode
    | AnyNode[]
    | Cheerio<AnyNode>
    | ((i: number, html: string) => string | AnyNode | Cheerio<AnyNode>)
  )[]
): Cheerio<T>;

参数:

名称 类型 默认值 描述
contents string | AnyNode | Cheerio | function - 要追加的内容

返回值: Cheerio<T> - 原始 Cheerio 实例

示例:

// Append HTML string
$('ul').append('<li>New item</li>');

// Append multiple items
$('ul').append('<li>Item 1</li>', '<li>Item 2</li>');

// Append Cheerio object
const $newLi = $('<li>').text('Dynamic item');
$('ul').append($newLi);

// Function-based appending
$('div').append((i, html) => `<p>Section ${i + 1}</p>`);

.remove(selector?)

从 DOM 中移除匹配的元素。

函数签名:

function remove(selector?: string): Cheerio<T>;

参数:

名称 类型 默认值 描述
selector string - 过滤移除的可选选择器

返回值: Cheerio<T> - 被移除的元素

示例:

// Remove all matched elements
$('.obsolete').remove();

// Remove with filtering
$('li').remove(':contains("delete")'); // Remove <li> containing "delete"

// Chain after removal
$('p').remove().appendTo('.archive'); // Move to archive

CSS 和样式

.css(property, value?)

获取或设置元素的 CSS 样式。

函数签名:

// Get style
function css(property: string): string | undefined;
// Set style
function css(property: string, value: string | ((i: number, style: string) => string)): Cheerio<T>;
// Set multiple styles
function css(properties: Record<string, string>): Cheerio<T>;
// Get multiple styles
function css(properties: string[]): Record<string, string>;

参数:

名称 类型 默认值 描述
property string | string[] | Record<string, string> - CSS 属性名、数组或对象
value string | function - 要设置的 CSS 值或函数

返回值: string \| Record<string, string> \| Cheerio<T> - CSS 值或 Cheerio 实例

示例:

// Get computed style
const color = $('.highlight').css('color'); // "red"

// Set single style
$('.box').css('background-color', 'blue');

// Set multiple styles
$('.card').css({
  'border-radius': '8px',
  'box-shadow': '0 2px 4px rgba(0,0,0,0.1)',
  padding: '16px'
});

// Function-based setting
$('div').css('width', (i, width) => `${parseInt(width) + 10}px`);

.addClass(className)

向匹配元素添加 CSS 类。

函数签名:

function addClass(
  className: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;

参数:

名称 类型 默认值 描述
className string | function - 空格分隔的类名或函数

返回值: Cheerio<T> - 用于链式调用的 Cheerio 实例

示例:

// Add single class
$('.item').addClass('active');

// Add multiple classes
$('.card').addClass('highlighted featured');

// Function-based adding
$('li').addClass((i, currentClass) => {
  return i % 2 === 0 ? 'even' : 'odd';
});

.removeClass(className?)

从匹配元素中移除 CSS 类。

函数签名:

function removeClass(
  className?: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;

参数:

名称 类型 默认值 描述
className string | function - 要移除的类或函数(省略则移除所有)

返回值: Cheerio<T> - 用于链式调用的 Cheerio 实例

示例:

// Remove specific class
$('.item').removeClass('active');

// Remove multiple classes
$('.card').removeClass('highlighted featured');

// Remove all classes
$('.temp').removeClass();

// Function-based removal
$('div').removeClass((i, currentClass) => {
  return currentClass.includes('temp-') ? currentClass : '';
});

.hasClass(className)

检查任何匹配元素是否具有指定的 CSS 类。

函数签名:

function hasClass(className: string): boolean;

参数:

名称 类型 默认值 描述
className string - 要检查的类名

返回值: boolean - 如果任何元素具有该类则为 true

示例:

// Check for class
if ($('.nav-item').hasClass('active')) {
  console.log('Found active navigation item');
}

// Conditional logic
$('.button').each(function() {
  if ($(this).hasClass('primary')) {
    $(this).css('font-weight', 'bold');
  }
});

遍历和过滤

.find(selector)

搜索匹配选择器的后代元素。

函数签名:

function find<T extends AnyNode>(selector: string): Cheerio<T>;

参数:

名称 类型 默认值 描述
selector string - 要搜索的 CSS 选择器

返回值: Cheerio<T> - 找到的后代元素集合

示例:

// Find descendants
const links = $('.nav').find('a'); // All <a> tags inside .nav

// Complex selectors
const activeLinks = $('.menu').find('li.active a[href]');

// Chain with other methods
$('.article').find('img').attr('loading', 'lazy');

.each(callback)

遍历匹配的元素,为每个元素执行回调函数。

函数签名:

function each(
  callback: (this: T, i: number, el: T) => void | false
): Cheerio<T>;

参数:

名称 类型 默认值 描述
callback function - 为每个元素执行的函数

返回值: Cheerio<T> - 原始 Cheerio 实例

示例:

// Basic iteration
$('li').each(function(i, el) {
  console.log(`Item ${i}: ${$(el).text()}`);
});

// Early termination
$('.item').each(function(i) {
  if ($(this).hasClass('stop')) return false; // Break loop
  $(this).addClass(`item-${i}`);
});

// Arrow function (note: `this` context differs)
$('img').each((i, img) => {
  $(img).attr('alt', `Image ${i + 1}`);
});

常见陷阱:

表单处理

.serialize()

将表单元素序列化为 URL 编码的查询字符串。

函数签名:

function serialize(): string;

返回值: string - URL 编码的表单数据

示例:

// Serialize entire form
const formData = $('form').serialize();
// "name=John&email=john%40example.com&subscribe=on"

// Serialize specific inputs
const inputData = $('input[type="text"], select').serialize();

.serializeArray()

将表单元素序列化为名值对象数组。

函数签名:

function serializeArray(): Array<{ name: string; value: string }>;

返回值: Array<{ name: string; value: string }> - 表单数据对象数组

示例:

// Get structured form data
const formArray = $('form').serializeArray();
// [{ name: 'email', value: 'user@example.com' }, { name: 'subscribe', value: 'on' }]

// Convert to object
const formObject = {};
$('form').serializeArray().forEach(item => {
  formObject[item.name] = item.value;
});

常见陷阱: