基于node下的http小爬虫的示例代码

2020-06-17 07:11:24易采站长站整理

当然爬个HTML对于我们来说没啥用,现在我们要做些过滤,比如这个node教程中我想知道课程目录有哪些,这样可以选择感兴趣的去看看学学。直接上代码吧还是:

不过在此之前我们需要下载cheerio模块(cheerio是nodejs的抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现。适合各种Web爬虫程序。)具体详细介绍你们可以自行去搜索了解,cheerio的用跟jquery的用法非常类似,所以不用担心上手繁琐。


PS G:nodenode-http> npm install cheerio

建立node-http-more.js,其中代码如下:


var http=require('http');//获取http模块
var cheerio=require('cheerio');//引入cheerio模块
var url='http://www.runoob.com/nodejs/nodejs-tutorial.html';//定义node官网地址变量
// filer node chapter
function filerNodeChapter(html){
// 将爬取得HTML装载起来
var $=cheerio.load(html);
// 拿到左侧边栏的每个目录
var nodeChapter=$('#leftcolumn a');
//这里我希望我能获取的到的最终数据格式这个样子的,如此我们能知道每个目录的地址及标题
/**
* [{id:,title:}] */
var chapterData=[];
nodeChapter.each(function(item){
// 获取每项的地址及标题
var id=$(this).attr('href');
var title=$(this).text();
chapterData.push({
id:id,
title:title
})
})

return chapterData;

}

//获取每个数据
function getChapterData(nodeChapter){
nodeChapter.forEach(function(item){
console.log(' 【 '+item.id+' 】'+item.title+'n')
});
}

http.get(url,function(res){
var html='';

// 这里将会触发data事件,不断触发不断跟新html直至完毕
res.on('data',function(data){
html +=data
})

// 当数据获取完成将会触发end事件,这里将会打印初node官网的html
res.on('end',function(){
//console.log(html)
// 过滤出node.js的课程目录
var nodeChapter= filerNodeChapter(html);

//循环打印所获取的数据
getChapterData(nodeChapter)
})
}).on('error',function(){
console.log('获取node官网相关数据出错')
})

终端执行结果及打印出课程目录


G:nodenode-http> node node-http-more.js
【 /nodejs/nodejs-tutorial.html 】
Node.js 教程

【 /nodejs/nodejs-install-setup.html 】
Node.js 安装配置

【 /nodejs/nodejs-http-server.html 】
Node.js 创建第一个应用

【 nodejs-npm.html 】 NPM 使用介绍

【 nodejs-repl.html 】 Node.js REPL

【 nodejs-callback.html 】 Node.js 回调函数

【 nodejs-event-loop.html 】 Node.js 事件循环