node.js实现博客小爬虫的实例代码

爬虫,是一种自动获取网页内容的程序。是搜索引擎的重要组成部分,因此搜索引擎优化很大程度上就是针对爬虫而做出的优化。

这篇文章介绍的是利用node.js实现博客小爬虫,核心的注释我都标注好了,可以自行理解,只需修改url和按照要趴的博客内部dom构造改一下filterchapters和filterchapters1就行了!

下面话不多说,直接来看实例代码

var http=require('http'); var Promise=require('Bluebird'); var cheerio = require('cheerio'); var url='http://www.immaster.cn';//博客地址 function filterchapters1(html) {//解析文章链接 var $ =cheerio.load(html); var post=$('.post'); var content=[]; post.each(function (item) { var postid=$(this).find('.tit').find('a').attr('href'); content.push(postid); }) return content; } function filterchapters(html) {//解析每个文章内的内容 var $ =cheerio.load(html); var tit=$('.post .tit').find('a').text(); var postid=$('.tit').find('a').attr('href'); var commentnum=$('.comments-title').text(); commentnum=commentnum.trim(); // commentnum=commentnum.replace('\n',''); var content={tit:tit,url:postid,commentnum:commentnum}; return content; } function getid(url){//爬取首页文章链接 return new Promise(function (resolve,reject) { http.get(url,function (res) { var html = ''; res.on('data',function(data) { html+=data; }); res.on('end',function () { var content=filterchapters1(html) resolve(content); }) }).on('error',function () { reject(e); console.log('抓取出错!') }) }) } function getpageAsync(url) {//爬取单个页面内容 return new Promise(function (resolve,reject) { console.log('正在爬取……'+url) http.get(url,function (res) { var html = ''; res.on('data',function(data) { html+=data; }); res.on('end',function () { resolve(html); }) }).on('error',function () { reject(e); console.log('抓取出错!') }) }) } getid(url) .then(function(postid){ return new Promise(function (resolve,reject) { var pageurls=[]; postid.forEach(function (id) { pageurls.push(getpageAsync(id)); }) resolve(pageurls); }) }) .then(function(pageurls){ return new Promise.all(pageurls);//让promise对象同时开始运行 }) .then(function (pages) { var coursesData=[]; pages.forEach(function (html) { var courses=filterchapters(html); coursesData.push(courses); }) coursesData.forEach(function(v){ console.log('标题:'+v.tit+"\n地址:"+v.url+"\n评论:"+v.commentnum) }) })

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzjyzp.html