用node.js爬取自己所有博客的名字,評論數,閱讀數和發佈時間

我們事先要對當前項目初始化,本地安裝gulp。
不懂得可以看我上一篇博客

代碼如下:

//引入https和cheerio模塊
const https = require('https')
var cheerio = require('cheerio');
//定義自己的博客請求地址
const url = 'https://blog.csdn.net/weixin_45991188'
//調用https.get()去請求
https.get(url,(res) =>{
    let raw = ''
    //監聽res data事件,可能會響應多次
    res.on('data',(chunk)=>{
        raw += chunk
    })
    //監聽res end事件,響應傳輸完觸發
    res.on('end',()=>{
        findMenu(raw);
    })
})
function findMenu(htmlstr){
    const b = cheerio.load(htmlstr)//獲取整個頁面的html
    var result = []//設置一個空數組
    //遍歷.article-item-box的每個元素,爲每個匹配元素規定要運行的函數
    b('.article-item-box').each(function(i, item) {
    var $h4 = b(item).find('h4').text().trim()//獲取到博客標題
    var $date = b(item).find('.date').text().trim()//獲取博客時間
    var $readnum = b(item).find('.read-num').text().trim()//獲取博客的閱讀數和評論數
    result.push($h4)//把的得到的值添加到result這個空數組
    result.push(`發佈時間: ${$date}`)
    result.push($readnum)
    })
    //最後打印出整個數組
    console.log(result)
}

然後我們在終端進入當前文件輸入node index.js
效果如下:
在這裏插入圖片描述
cheerio 第三方模塊
鏈接
簡單理解爲是使用在服務器端的 jquery。保留了 jquery 選擇器的相關功能,去掉了 DOM 操作功能。

  1. 安裝模塊
    cnpm i cheerio -D

  2. 引入
    const cheerio = require('cheerio')

  3. 裝載
    const b = cheerio.load('<h2 class="title">Hello world</h2>')

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