码迷,mamicode.com
首页 > Web开发 > 详细

Node.js 爬虫初探

时间:2015-12-06 22:39:51      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

前言

      在学习慕课网视频和Cnode新手入门接触到爬虫,说是爬虫初探,其实并没有用到爬虫相关第三方类库,主要用了node.js基础模块http、网页分析工具cherrio。 使用http直接获取url路径对应网页资源,然后使用cherrio分析。 这里我主要是把慕课网教学视频提供的案例自己敲了一边,加深理解。在coding的过程中,我第一次把jq获取后的对象直接用forEach遍历,直接报错,是因为jq没有对应的这个方法,只有js数组可以调用。

 

知识点

    ①:superagent抓去网页工具。我暂时未用到。

    ②:cherrio 网页分析工具,你可以理解其为服务端的jQuery,因为语法都一样。

 

效果图

1、抓取整个网页

技术分享

 

2、分析后的数据, 我这里是以慕课网提供的示例为案例实现的例子。

技术分享

 

爬虫初探源码分析

var http=require(‘http‘);
var cheerio=require(‘cheerio‘);

var url=‘http://www.imooc.com/learn/348‘;

/****************************
打印得到的数据结构
[{
	chapterTitle:‘‘,
	videos:[{
		title:‘‘,
		id:‘‘
	}]
}]
********************************/
function printCourseInfo(courseData){
	courseData.forEach(function(item){
		var chapterTitle=item.chapterTitle;
		console.log(chapterTitle+‘\n‘);
		item.videos.forEach(function(video){
			console.log(‘ 【‘+video.id+‘】‘+video.title+‘\n‘);
		})
	});
}


/*************
分析从网页里抓取到的数据
**************/
function filterChapter(html){
	var courseData=[];

	var $=cheerio.load(html);
	var chapters=$(‘.chapter‘);
	chapters.each(function(item){
		var chapter=$(this);
		var chapterTitle=chapter.find(‘strong‘).text(); //找到章节标题
		var videos=chapter.find(‘.video‘).children(‘li‘);

		var chapterData={
			chapterTitle:chapterTitle,
			videos:[]
		};

		videos.each(function(item){
			var video=$(this).find(‘.studyvideo‘); 
			var title=video.text();
			var id=video.attr(‘href‘).split(‘/video‘)[1];

			chapterData.videos.push({
				title:title,
				id:id
			})
		})

		courseData.push(chapterData);
	});

    return courseData;
}

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

	res.on(‘data‘,function(data){
		html+=data;
	})

	res.on(‘end‘,function(){
		var courseData=filterChapter(html);
		printCourseInfo(courseData);
	})
}).on(‘error‘,function(){
	console.log(‘获取课程数据出错‘);
})

 

参考资料

https://github.com/alsotang/node-lessons/tree/master/lesson3

http://www.imooc.com/video/7965

Node.js 爬虫初探

标签:

原文地址:http://www.cnblogs.com/sword-successful/p/5024579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!