NodeJS解析HTML之cheerio

版权声明:本文为博主原创文章,欢迎转载,转载时请以超链接形式标明文章原始出处。 https://blog.csdn.net/lilongsy/article/details/83652266

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('<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>

参考

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

猜你喜欢

转载自blog.csdn.net/lilongsy/article/details/83652266