用于解析和操作 HTML 和 XML 的快速、灵活且优雅的库。
import * as cheerio from 'cheerio';
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html();
//=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
使用 npm、yarn 或 bun 等包管理器安装 Cheerio。
npm install cheerio
# 或
bun add cheerio
❤ 经过验证的语法: Cheerio 实现了 jQuery 核心的一个子集。Cheerio从 jQuery 库中移除了所有 DOM 不一致和浏览器冗余,从而展现了其真正优秀的 API。
ϟ 极快: Cheerio 采用非常简单、一致的 DOM模型。因此,解析、操作和渲染都非常高效。
❁极其灵活: Cheerio 封装了parse5 来解析 HTML,并可选择使用更强大的 htmlparser2。Cheerio几乎可以解析任何 HTML 或 XML 文档。Cheerio 可在浏览器和服务器环境中运行。
首先,你需要加载 HTML。在 jQuery 中,这一步是隐式的,因为jQuery 操作的是内置的 DOM。而使用 Cheerio,我们需要传入HTML 文档。
// ESM or TypeScript:
import * as cheerio from 'cheerio';
// In other environments:
const cheerio = require('cheerio');
const $ = cheerio.load('<ul id="fruits">...</ul>');
$.html();
//=> <html><head></head><body><ul id="fruits">...</ul></body></html>
加载 HTML 后,您可以使用 jQuery 风格的选择器在文档中查找元素。
selector
在 context
作用域内搜索,而 context
作用域又在 root
作用域内搜索。
selector
和 context
可以是字符串表达式、DOM 元素、DOM 元素数组或 cheerio 对象。root
(如果提供)通常是 HTML文档字符串。
此选择器方法是遍历和操作文档的起点。与 jQuery 类似,它是在文档中选择元素的主要方法。
$('.apple', '#fruits').text();
//=> Apple
$('ul .pear').attr('class');
//=> pear
$('li[class=orange]').html();
//=> Orange
当您准备好渲染文档时,可以在“根”选择上调用 html
方法:
$.root().html();
//=> <html>
// <head></head>
// <body>
// <ul id="fruits">
// <li class="apple">Apple</li>
// <li class="orange">Orange</li>
// <li class="pear">Pear</li>
// </ul>
// </body>
// </html>
如果您想要渲染outerHTML
选定内容,您可以使用 outerHTML
属性:
$('.pear').prop('outerHTML');
//=> <li class="pear">Pear</li>
您还可以使用 text
方法渲染 Cheerio 对象的文本内容:
const $ = cheerio.load('This is <em>content</em>.');
$('body').text();
//=> This is content.
Cheerio 集合由与基于浏览器的 DOM 节点 类似的对象组成。它们可以定义以下属性:
tagName
parentNode
previousSibling
nextSibling
nodeValue
firstChild
childNodes
lastChild
MIT