Step 1: 萬年不變的初始化項目,安裝依賴html
cnpm i express cheerio superagent superagent-charset async -S
express 就不用多說了,比較流行的node框架
cheerio 頁面數據解析模塊。通常都習慣稱它node版的jquery,專門用來操做網頁dom元素,使用方式和jquery基本相同。
superagent superagent是nodejs裏一個很是方便的客戶端請求代碼模塊,superagent是一個輕量級的,漸進式的ajax API,可讀性好,學習曲線低,內部依賴nodejs原生的請求API,適用於nodejs環境下。
superagent-charset 很明顯,處理編碼的。
async 見名知意,node的異步模塊。
Step 2: 編寫node程序node
/* 以爬取起點小說某文爲例 */ // 1. 首先引入模塊 const cheerio = require('cheerio') const express = require('express') const app = express() const superagent = require('superagent') require('superagent-charset')(superagent) const async = require('async'); let total = 0 // 總章節數 let id = 0 // 計數器 const chapter = 10 // 爬取多少章 const url = 'https://book.qidian.com/info/1011146676#Catalog' // 章節列表頁面
// 處理請求 app.get('/',(req,response,next)=>{ superagent.get(url).charset('UTF-8').end((err,res)=>{ var $ = cheerio.load(res.text); // 讀取章節列表頁面 let urls = [] total = $(".volume-wrap li").length // 獲取因此章節元素拿到總章節數
// 循環獲取每一個章節的頁面url並push進urls $('.volume-wrap li').each(function(i,v){ if(i < chapter){ urls.push('http:' + $(v).find("a").attr('href')) } }) // 經過async去請求urls裏的地址,並經過fetchUrl方法拆分數據。這裏的async.mapLimit方法有點相似es6裏的promise.all async.mapLimit(urls,chapter,(url,callback)=>{ id++ fetchUrl(url,callback,id); },(err,results)=>{ response.send(results); }) }) }) // 去空格和空格轉義字符 function trim(str){ return str.replace(/(^\s*)|(\s*$)/g, '').replace(/ /g, '') } // 將Unicode轉漢字 function reconvert(str) { str = str.replace(/(&#x)(\w{1,4});/gi, function ($0) { return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"), 16)); }); return str } // 加載每一個章節並拆分數據返回 function fetchUrl(url,callback,id){ superagent.get(url) .charset('UTF-8') .end(function(err,res){ let $ = cheerio.load(res.text); let arr = [] let content = reconvert($(".read-content").html()) const obj = { id: id, err: 0, bookName: $('.text-info a').eq(0).text().substring(1), title: $('.j_chapterName').text(), content: content.toString() } callback(null,obj) }) } // 監聽窗口 const PORT = 8080 app.listen(PORT,function(){ console.log("server listening on " + PORT) })
最後,運行node程序,本地打開localhost:8080 就能夠看到數據了jquery