cheerio简介

为服务器特别定制的,快速、灵活、实施的jQuery核心实现。

  • 易用,语法类似jQuery语法,从jQuery库中去除了所有 DOM不一致性和浏览器尴尬的部分。
  • 解析快,比JSDOM快八倍。
  • 灵活,Cheerio 封装了兼容的htmlparser。Cheerio 几乎能够解析任何的 HTML 和 XML document。

安装

npm install

cnpm install

简单使用

// 引入cheerio模块
const cheerio = require('cheerio')
// 加载HTML字符串
const $ = cheerio.load('<h2 class="title">Hello world</h2>')

// 设置Text
$('h2.title').text('Hello there!')
// 添加class
$('h2').addClass('welcome')

// 获取完整HTML
$.html()
//=> <html><head></head><body>
// <h2 class="title welcome">Hello there!</h2></body></html>

​load​​的默认配置:

{
withDomLvl1: true,
normalizeWhitespace: false,
xmlMode: true,
decodeEntities: true
}

如果想要获取的代码不实例化,可以设置​​decodeEntities​​​为​​false​​。

参考

  1. 官网:https://www.npmjs.com/package/cheerio
  2. ​https://github.com/fb55/DomHandler​