NodeJS解析HTML之cheerio

cheerio简介

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

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

安装

npm install cheerio

cnpm install cheerio

简单使用

// 引入cheerio模块
const cheerio = require('cheerio')
// 加载HTML字符串
const $ = cheerio.load('

Hello world

'
) // 设置Text $('h2.title').text('Hello there!') // 添加class $('h2').addClass('welcome') // 获取完整HTML $.html() //=> //

Hello there!

load的默认配置:

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

如果想要获取的代码不实例化,可以设置decodeEntitiesfalse

参考

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

你可能感兴趣的:(nodejs)