node.js实现博客小爬虫的实例代码
前言
爬虫,是一种自动获取网页内容的程序。是搜索引擎的重要组成部分,因此搜索引擎优化很大程度上就是针对爬虫而做出的优化。
这篇文章介绍的是利用node.js实现博客小爬虫,核心的注释我都标注好了,可以自行理解,只需修改url和按照要趴的博客内部dom构造改一下filterchapters和filterchapters1就行了!
下面话不多说,直接来看实例代码
varhttp=require('http'); varPromise=require('Bluebird'); varcheerio=require('cheerio'); varurl='http://www.immaster.cn';//博客地址 functionfilterchapters1(html){//解析文章链接 var$=cheerio.load(html); varpost=$('.post'); varcontent=[]; post.each(function(item){ varpostid=$(this).find('.tit').find('a').attr('href'); content.push(postid); }) returncontent; } functionfilterchapters(html){//解析每个文章内的内容 var$=cheerio.load(html); vartit=$('.post.tit').find('a').text(); varpostid=$('.tit').find('a').attr('href'); varcommentnum=$('.comments-title').text(); commentnum=commentnum.trim(); //commentnum=commentnum.replace('\n',''); varcontent={tit:tit,url:postid,commentnum:commentnum}; returncontent; } functiongetid(url){//爬取首页文章链接 returnnewPromise(function(resolve,reject){ http.get(url,function(res){ varhtml=''; res.on('data',function(data){ html+=data; }); res.on('end',function(){ varcontent=filterchapters1(html) resolve(content); }) }).on('error',function(){ reject(e); console.log('抓取出错!') }) }) } functiongetpageAsync(url){//爬取单个页面内容 returnnewPromise(function(resolve,reject){ console.log('正在爬取……'+url) http.get(url,function(res){ varhtml=''; 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){ returnnewPromise(function(resolve,reject){ varpageurls=[]; postid.forEach(function(id){ pageurls.push(getpageAsync(id)); }) resolve(pageurls); }) }) .then(function(pageurls){ returnnewPromise.all(pageurls);//让promise对象同时开始运行 }) .then(function(pages){ varcoursesData=[]; pages.forEach(function(html){ varcourses=filterchapters(html); coursesData.push(courses); }) coursesData.forEach(function(v){ console.log('标题:'+v.tit+"\n地址:"+v.url+"\n评论:"+v.commentnum) }) })
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用node.js实现爬虫能有所帮助,如果有疑问大家可以留言交流。