cheerio 庫學習(一)

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))


文檔未完,還有第二篇給大家介紹分析。
突然有點感想:知識是固定的,會靈活使用纔會發揮更大的價值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章