WEB

Cheerio模块

2017-05-16  本文已影响429人  Evtion

jquery库是前端操作dom节点的一把利手;在后端模块,cheerio模块是爬虫脚本用得最多的模块,主要用来获取爬取到的节点,cheeio模块的github地址是cheerio模块;下面看一下作者的文档。

1. Cheerio简介:
2. Cheerio示例代码:
const cheerio = require('cheerio')
const $ = cheerio.load('<h2 class="title">Hello world</h2>')

$('h2.title').text('Hello there!')
$('h2').addClass('welcome')

$.html()
//=> <h2 class="title welcome">Hello there!</h2>
3. API 说明:
<ul id="fruits">
  <li class="apple">Apple</li>
  <li class="orange">Orange</li>
  <li class="pear">Pear</li>
</ul>

const $ = cheerio.load('<ul id="fruits">...</ul>');
```
- 或者,也可以通过将字符串作为上下文加载到HTML中:

```
const $ = require('cheerio');
$('ul', '<ul id="fruits">...</ul>');
```
- 又或者作为根元素:
```
const $ = require('cheerio');
$('li', 'ul', '<ul id="fruits">...</ul>');
```
- 如果需要修改任何默认解析选项,你可以通过一个额外的对象给load()方法:
```
const $ = cheerio.load('<ul id="fruits">...</ul>', {
      normalizeWhitespace: true,
      xmlMode: true
});
```
- 这些options选项直接继承自htmlpaser2语法,因此任何选项来自htmlparser在cheerio中是可以直接使用的。下面是默认的options选项值:
```
{
    withDomLvl1: true,
    normalizeWhitespace: false,
    xmlMode: false,
    decodeEntities: true
}
```
- 要详细了解这些默认的options选项可以参考htmlparser2的options。
上一篇 下一篇

猜你喜欢

热点阅读