关于cheerio的api的学习笔记(一)

关于cheerio的api的学习笔记

我看的文档

因为这两周都在看Node.js实现爬虫的部分,对于cheerio这个模块的运用总是有问题出现,然后上网找了cheeriode API然后结合翻译看了一下。下面就是这一部分的学习笔记。
ps.这一部分是从loading 到 traversing

前言


cheerio是一款非常使用的nodejs第三方包,适用于nodejs端处理html(xml也可以),它有着与jquery及其相似的api,速度飞快,使用灵活。

cheerio 分析标记, 并提供用于遍历/操作生成的数据结构的 api。它不会像 web 浏览器那样解释结果。具体来说, 它不会生成可视化呈现、应用 css、加载外部资源或执行 javascript。如果您的用例需要任何此功能, 则应考虑 phantomjs 或 jsdom 等项目。

cheerio文档的api主要可以分为下面几个方面,

  • 加载(loading)
  • 选择器(selectors)
  • 属性操作(attributes)
  • 结构推导(traversing)
  • 结构操作(manipulation)
  • 实用方法(Miscellaneous & Utilities)

下面是这里所有api操作的示例html代码:

<ul id="fruits">
    <li class="apple">Apple</li>
    <li class="orange">Orange</li>
    <li class="pear">Pear</li>
</ul>

特(优)点概述:


  • ?相似的语法:cheerio包括jQuery核心的子集。cheerio从jQuery库中去除了所有DOM不一致性和浏览器尴尬的部分。
  • ⚡闪电般的块:cheerio工作在一个非常i暗淡,一致的DOM模型之上。解析,操作,呈送都变得难以置信的高效。基础的端到端基准测试显示cheerio大约比JSDOM快八倍。
  • ?巨灵活:cheerio封装了兼容的htmlparser,cheerio几乎能够解析任何的HTML和XML document。

加载(loading)


在使用cheerio进行各种操作之前,我们需要首先加载一份html得到一个cheerio对象。

比如:

const cheerio = require('cheerio');
const $ = cheerio.load('<ul>...</ul>');	//里面放html代码

或者:

使用$( selector, [context], [root] )这个api来获得部分html节点作为cheerio对象

const $ = require('cheerio');
$('ul','<ul>...</ul>');

或者:

也是使用$( selector, [context], [root] )这个api来获得部分html节点作为cheerio对象

const $ = require('cheerio');
$('li','ul','<ul>...</ul>');

也可以传递一个额外的对象给.load()如果你需要更改任何的默认解析选项的话:

const $ = cheerio.load('<ul>...</ul>',{
    ignoreWhiitespace: true,
    xmlMode: true
});

这些解析选项都直接来自于htmlparser,因此任何在htmlparser里优先的选项在cheerio里面都行得通。默认选项如下:

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

选择器(selectors)


$(select, [context], [root])

其中:

  • select:是目标选择器
  • context:是目标选择器的上下文
  • root:是上下文context的上下文

select(选择器)在context范围内搜索,context又在root范围内搜索。select和context可以是字符串表达式、dom元素、dom元素集合、cheerio对象,而root一般都是html文档字符串。

此选择器方法是遍历和操作文档的起点。

$('.apple', '#fruits').text()
//=> Apple

$('ul .pear').attr('class')
//=> pear

$('li[class=orange]').html()
//=> Orange

属性操作(attributes)


.attr(name, value)

该方法仅获取第一个参数的属性值。要单独获取每个参数的值,请使用循环结构,You may also pass a map and function like jQuery。

用来获取或设置属性的方法。当只有第一个参数时表示获取属性的值,当带有第二个参数时,表示设置属性的值。

$('ul').attr('id')
//=> fruits

$('.apple').attr('id', 'favorite').html()
//=> <li class="apple" id="favorite">Apple</li>

.prop(name, value)

$('input[type="checkbox"]').prop('checked')
//=> false

$('input[type="checkbox"]').prop('checked', true).val()
//=> ok

.data(name, value)

$('<div data-apple-color="red"></div>').data()
//=> { appleColor: 'red' }

$('<div data-apple-color="red"></div>').data('apple-color')
//=> 'red'

const apple = $('.apple').data('kind', 'mac')
apple.data('kind')
//=> 'mac'

.val( [value] )

.val()方法主要用于获取表单元素的值,如inputselecttextarea。当调用空集合时,它返回undefined

$('input[type="text"]').val()
//=> input_text

$('input[type="text"]').val('test').html()
//=> <input type="text" value="test"/>

.removeAttr( name )

通过name移除某一个属性,同时返回被移除的这个元素

$('.pear').removeAttr('class').html()
//=> <li>Pear</li>

.hasClass(className)

判断选择到的任何一个元素的class是否包含给出的 ‘className’;

Check to see if any of the matched elements have the given className.

$('.pear').hasClass('pear')
//=> true

$('apple').hasClass('fruit')
//=> false

$('li').hasClass('pear')
//=> true

.addClass(className)

给选中元素(可以多个)增加样式名(可以多个),也可以和jquery一样传函数。

Adds class(es) to all of the matched elements. Also accepts a function like jQuery.

$('.pear').addClass('fruit').html()
//=> <li class="pear fruit">Pear</li>

$('.apple').addClass('fruit red').html()
//=> <li class="apple fruit red">Apple</li>

注意,这个方法只会添加不会替换。

.removeClass(className)

将选中元素中名为className的样式删除。如果不存在className,就删除所有的样式名。

多个className用空格分隔(上面的addClass和hasClass也是)

$('.pear').removeClass('pear').html()
//=> <li class="">Pear</li>

$('.apple').addClass('red').removeClass().html()
//=> <li class="">Apple</li>

.toggleClass(className, [switch])

根据参数(className), 从选择的元素中添加或删除类([switch])。像jquery一样也接收函数。

$('.apple.green').toggleClass('fruit green red').html()
//=> <li class="apple fruit red">Apple</li>

$('.apple.green').toggleClass('fruit green red', true).html()
//=> <li class="apple green fruit red">Apple</li>
//[switch]为true时添加元素
//[switch]为false时相同的删除不同的添加

.is()

.is(selector)
.is(element)
.is(selection)
.is( function( index ) )

Checks the current list of elements and returns true if any of the elements match the selector. If using an element or Cheerio selection, returns true if any of the elements match. If using a predicate function, the function is executed in the context of the selected element, so this refers to the current element.

有任何元素匹配selector就返回true。如果使用判定函数,判定函数在选中的元素中执行,所以this指向当前的元素。

Forms

.serialize()

Encodes a set of form elements as a URL query string.

将一组表单元素(form)转码为url字符串

$('<form><input name="foo" value="bar" checked /><input name="foo" value="qux" checked /></form>').serialize()
//=> foo=bar&foo=qux
.serialzeArray()

Encode a set of form elements as an array of names and values.

将一组表单元素转码成数组

$('<form><input name="foo" value="bar" /></form>').serializeArray()
//=> [ { name: 'foo', value: 'bar' } ]

结构推导(traversing)


.find()

.find(selector)
.find(selection)
.find(node)

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

获取当前匹配元素集合中每个元素的后代, 由选择器、jquery 对象或元素进行筛选。

$('#fruits').find('li').length
//=> 3
$('#fruits').find($('.apple')).length
//=> 1

.parent([selector])

Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

获取当前匹配元素集合中每个元素的父元素, 由选择器进行筛选。

$('.pear').parent().attr('id')
//=> fruits

.parents([selector])

Get a set of parents filtered by selector of each element in the current set of match elements.

获得当前匹配元素集合中每个元素的parent集合。

$('.orange').parents().length
// => 3
//ul body html
$('.orange').parents('#fruits').length
// => 1

.parentsUntil([selector][,filter])

获得当前匹配元素集合中每个元素的祖先元素,直到(但不包括)被选择器、DOM 节点或 cheerio对象匹配的元素。

  • [selector]:字符串值,规定在何处停止对祖先元素进行匹配的选择器表达式。
  • [filter]:字符串值,包含用于匹配元素的选择器表达式。

.closet(seletor)

获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。

$('.orange').closest()
// => []
$('.orange').closest('.apple')
// => []
$('.orange').closest('li')
// => [<li class="orange">Orange</li>]
$('.orange').closest('#fruits')
// => [<ul id="fruits"> ... </ul>]

.next([selector])

获得第一个本元素之后的同级元素

$('.apple').next().hasClass('orange')
//=> true

.nextAll([selector])

获得本元素之后的所有同级元素

$('.apple').nextAll()
//=> [<li class="orange">Orange</li>, <li class="pear">Pear</li>]
$('.apple').nextAll('.orange')
//=> [<li class="orange">Orange</li>]

.nextUntil([selector],[filter])

获得每个元素所有跟随的同胞元素,但不包括被选择器、DOM 节点匹配的元素。

  • selector:字符串值,包含指示在何处停止匹配跟随的同胞元素的选择器表达式。
  • filter:字符串值,包含用于匹配元素的选择器表达式。

.prev([selector])

获得本元素之前的第一个同级元素

$('.orange').prev().hasClass('apple')
//=> true

.prevAll([selector])

获得本元素前所有同级元素

$('.pear').prevAll()
//=> [<li class="orange">Orange</li>, <li class="apple">Apple</li>]
$('.pear').prevAll('.orange')
//=> [<li class="orange">Orange</li>]

.prevUntil([selector], [filter])

获得当前匹配元素集合中每个元素的前面的同胞元素,但不包括被选择器、DOM 节点匹配的元素。

$('.pear').prevUntil('.apple')
//=> [<li class="orange">Orange</li>]

.slice( start, [end] )

获得选定范围内所有元素

$('li').slice(1).eq(0).text()
//=> 'Orange'

$('li').slice(1, 2).length
//=> 1

.siblings([selector])

获得选中元素的所有同级元素(除去自己)

$('.pear').siblings().length
//=> 2

$('.pear').siblings('.orange').length
//=> 1

.children([selector])

获得被选中元素的所有直接子元素

$('#fruits').children().length
//=> 3

$('#fruits').children('.pear').text()
//=> Pear

.contents()

获得匹配元素集合中每个元素的子节点,包括文本和注释节点。

$('#fruits').contents().length
//=> 3

.each(function(index, element))

each() 方法规定为每个匹配元素规定运行的函数。返回 false 可用于及早停止循环。

const fruits = [];

$('li').each(function(i, elem) {
  fruits[i] = $(this).text();
});

fruits.join(', ');
//=> Apple, Orange, Pear
  • function(index,element):必需。为每个匹配元素规定运行的函数。
    • index :选择器的 index 位置
    • element:当前的元素(也可使用 “this” 选择器)

.map(function(index, element))

通过函数传递当前匹配集中的每个元素, 生成包含返回值的新 cheerio 对象。(和jquery类似的each迭代器,对每一个元素进行处理并返回一个值。)

$('li').map(function(i, el) {
  // this === el
  return $(this).text();
}).get().join(' ');
//=> "apple orange pear"

.filter()

.filter(selector)
.filter(selection)
.filter(element)
.filter(function(index, element))

在cheerio对象集合中进行条件筛选。迭代cheerio对象,滤出匹配选择器或者是传进去的函数的元素。如果使用函数方法,这个函数在被选择的元素中执行,所以this指向的手势当前元素。

  • Selector:
$('li').filter('.orange').attr('class');
//=> orange
  • Function:
$('li').filter(function(i, el) {
  // this === el
  return $(this).attr('class') === 'orange';
}).attr('class')
//=> orange

.not()

.not(selector)
.not(selection)
.not(element)
.not(function(index, elem))

从匹配的元素集中删除元素。

给定一个表示一组 dom 元素的 jquery 对象,方法从匹配元素的子集中构造一个新的 jquery 对象。提供的选择器将针对每个元素进行测试,与选择器不匹配的元素将包含在结果中。

这个方法可以像. filter ()一样将函数作为其参数。函数返回 true 的元素将从新对象中排除,所有其他元素将被包括在新对象中。

  • Selector:
$('li').not('.apple').length;
//=> 2
  • Function:
$('li').not(function(i, el) {
  // this === el
  return $(this).attr('class') === 'orange';
}).length;
//=> 2

.has(selector)

.has(element)

将匹配元素集合缩减为拥有匹配指定选择器或 DOM 元素的后代的子集。所使用的选择器用于检测匹配元素的后代;如果任何后代元素匹配该选择器,该元素将被包含在结果中。

  • Selector:
$('ul').has('.pear').attr('id');
//=> fruits
  • Element:
$('ul').has($('.pear')[0]).attr('id');
//=> fruits

.first()

会选择chreeio对象的第一个元素。

$('#fruits').children().first().text()
//=> Apple

.last()

会选择chreeio对象的最后一个元素。

$('#fruits').children().last().text()
//=> Pear

.eq(i)

通过索引筛选匹配的元素。使用.eq(-i)就从最后一个元素向前数。

$('li').eq(0).text()
//=> Apple

$('li').eq(-1).text()
//=> Pear

.get([i])

检索由 cheerio 对象匹配的 dom 元素。如果指定了索引, 则返回由 cheerio 对象匹配的元素的其中一个(由 i 决定),如果未指定索引,则检索由 cheerio 对象匹配的所有元素。

$('li').get(0).tagName
//=> li
$('li').get().length
//=> 3

.index()

.index( selector )
.index( nodeOrSelection )

返回指定元素相对于其他指定元素的 index 位置

$('.pear').index()
//=> 2
$('.orange').index('li')
//=> 1
$('.apple').index($('#fruit, li'))
//=> 1
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值