cheerio 库学习(一)

Cheerio是一款专为服务器端设计的快速、高效jQuery核心库,它消除了DOM冲突和浏览器兼容性问题,提供了与jQuery相同的熟悉语法。Cheerio运行速度极快,比JSDOM渲染速度快8倍,并且能够解析HTML和XML,支持多种加载和选择器方式。

cheerio


​ 这个库是特别为服务器端实现的一个快速敏捷的Jquery核心库。

安装
npm install cheerio --save
特点
  • 熟悉的语法:它的实现是基于Jquery的核心库。它从Jquery库中移除了所有DOM的冲突和令人不爽的浏览器的东西。
  • 迅速:它始终工作在一个持续的单一的DOM模型中。对于语法解析,手动操纵和渲染都是异常地迅速。以后端-后端的标准进行测试,结果发现cheerio的运行渲染速率是JSDOM渲染的8倍。
  • 方便到不可思议:cheerio包包括Parse5语法解析器并且可选性支持htmlparser2。它可以解析HTML和XML。
API
加载方式
  • 推荐方式:

    const cheerio = require('cheerio')
    const $ = cheerio.load('html doc')
    
  • 可选方式1:

    const $ = require('cheerio')
    $('li','ul','html doc')
    
  • 可选方式2:

    /**
    * 如果要选择解析器为XML 直接在load方法中,改变可选选项的内容即可
    */
    const $ = cheerio.load('xml doc',{
      xml:{
        normalizeWhitespace:true,
        withDomLvl1:true,
        xmlMode:true,
        decodeEntities:true
      }
    })
    
选择器

​ 由于cheerio核心是选取的jquery库,所以加载方式对于一个前端程序员来说是十分的熟悉。

  • $( selector, [context], [root] )

    • selector是搜索的是根元素范围内的上下文。
    • selectorcontext可以使一个字符串表达式,一个DOM元素,一个DOM元素数组,更或者是一个cheerio对象。
    • root一般情况下是一个HTML的文本字符串。
    $('.apple','#fruit').text()
    $('ul .pear').attr('class')
    $('li[class=orange]').html()
    
属性
  • .attr(name,value)需要注意的是改变的是匹配到的第一个元素的值

    $('ul').attr('id') ##get method
    $('.apple').attr('id','favorite').html() ## set the element which class is apple
    
  • .prop(name,value)

    $('input[type="checkbox"]').prop('checked') ## return the first patched element boolean
    $('input[type="checkbox"]').prop('checked',true).val() ## return ok represent the value setted succeed.
    
  • .data(name,value)返回或者设置匹配到第一个元素的属性

    $('<div data-apple-color="red"></div>').data()
    ## =>{ appleColor: 'red' }
    $('<div data-apple-color="red"></div>').data('appleColor')
    ## => red
    const apple = $('.apple').data('kind', 'mac')
    apple.data('kind')
    ## => mac  set the kind as mac. apple.data is stated the result after manipulate.
    
  • .val(name,value)

    /**
    * 	返回或者设置 input select textarea的值
    */
    $('input[type="text"]').val()
    ## => get the input default val is input_text
    $('input[type="text"]').val('test').html()
    ## => set the input value is test. The result is test.
    
  • .removeAttr(name,value)

    /**
    *  通过名字移除属性,这个名字可以使id名或者类名
    */
    $('.pear').removeAttr('class').html() 
    ## => 显示的是移除类名为pear的类
    $('#pear').removeAttr('class').html()
    ## => 自行体会
    
  • .hasClass(name,value)

  • .addClass(name,value)

  • .removeClass(name,value)

  • .toggleClass(name,value)

  • .is(Selector)&& .is(element)&& .is(selection)&& .is(function(index))


文档未完,还有第二篇给大家介绍分析。
突然有点感想:知识是固定的,会灵活使用才会发挥更大的价值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yao.Li

爱的魔力,一被卡布奇诺~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值