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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

蛋炒饭   2020-05-15 我要评论

前言

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

这篇文章介绍的是利用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)
 })
 })

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用node.js实现爬虫能有所帮助,如果有疑问大家可以留言交流。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们