node 爬蟲(-)

var eventproxy = require('eventproxy');//併發控制
var express = require('express');
var utility = require('utility');//utility.md5('aaa')轉md5
var superagent = require('superagent');//ajax請求
var cheerio = require('cheerio');//頁面dom操做,jq
var app = new express();
var url = require('url');
var ep = new eventproxy();

app.get('/', function (req, res, next) {//本地頁面訪問路徑,訪問後執行 http://localhost:3000/

superagent.get('http://wiki.jikexueyuan.com/project/node-lessons/superagent-cheerio.html').end(function (err, sres) {//訪問源網址拿到其中更多頁面的網址
 
// 常規的錯誤處理
if (err) {
  return next(err);
}
 
var urlArr = [];//須要獲取的連接數組
var $ = cheerio.load(sres.text);//sres.text可獲取頁結構,經過cherrio轉爲jq對象

$('.detail-navlist-title a').each(function(i,e){
  var href = $(e).attr('href');
  urlArr.push(href);
})

console.log(urlArr);

urlArr.forEach(ele => {//對獲取的連接數組進行遍歷請求
  superagent.get(ele).end(function(err,sres){
    ep.emit('countnum',sres.text);//觸發計數器countnum,
  })
});

ep.after('countnum',urlArr.length,function(datas){//監聽計數器countnum,當次數達到urlArr.length時觸發回調,datas爲全部觸發countnum時的參數sres.text集合
  datas = datas.map(function(dom){
  var $ = cheerio.load(dom);//每一個頁面的dom結構
  return ({
    title:$('.markdown-body h1').html()
  })
})
console.log(datas)
res.setHeader('content-type', 'text/html;charset=gb2312');//指定響應編碼,不然亂碼
res.send(datas);//發送到頁面顯示
})
 

 
});
}).listen(3000);
相關文章
相關標籤/搜索