Cheerio 技术文档
1. 安装指南
1.1 使用 npm 安装
要安装 Cheerio,请在终端中运行以下命令:
npm install cheerio
1.2 使用 Yarn 安装
如果你使用 Yarn 作为包管理器,可以使用以下命令进行安装:
yarn add cheerio
2. 项目使用说明
2.1 加载 HTML
首先,你需要加载 HTML 文档。Cheerio 需要显式地传入 HTML 文档,这与 jQuery 不同,jQuery 默认操作的是浏览器中的 DOM。
// 使用 ESM 或 TypeScript
import * as cheerio from 'cheerio';
// 在其他环境中
const cheerio = require('cheerio');
const $ = cheerio.load('<ul id="fruits">...</ul>');
$.html();
//=> <html><head></head><body><ul id="fruits">...</ul></body></html>
2.2 选择器
加载 HTML 后,你可以使用 jQuery 风格的选择器来查找文档中的元素。
$('.apple', '#fruits').text();
//=> Apple
$('ul .pear').attr('class');
//=> pear
$('li[class=orange]').html();
//=> Orange
2.3 渲染
当你准备好渲染文档时,可以调用 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.
3. 项目 API 使用文档
3.1 加载 HTML
const $ = cheerio.load('<ul id="fruits">...</ul>');
3.2 选择器
$(selector, [context], [root]);
selector
:选择器字符串。context
:上下文,可选。root
:根节点,可选。
3.3 渲染
$.root().html();
3.4 获取 outerHTML
$('.pear').prop('outerHTML');
3.5 获取文本内容
$('body').text();
4. 项目安装方式
4.1 使用 npm 安装
npm install cheerio
4.2 使用 Yarn 安装
yarn add cheerio
通过以上步骤,你可以轻松地安装和使用 Cheerio 来解析和操作 HTML 和 XML 文档。Cheerio 提供了与 jQuery 类似的 API,使得开发者可以快速上手并高效地处理 DOM 操作。