Cheerio 技术文档

Cheerio 技术文档

cheerio The fast, flexible, and elegant library for parsing and manipulating HTML and XML. cheerio 项目地址: https://gitcode.com/gh_mirrors/ch/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 操作。

cheerio The fast, flexible, and elegant library for parsing and manipulating HTML and XML. cheerio 项目地址: https://gitcode.com/gh_mirrors/ch/cheerio

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏意杉Cub

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值