这里有新鲜出炉的 Node.js 教程,程序狗速度看过来!
Node.js 是一个基于 Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用 · Node.js 借助事件驱动, 非阻塞 I/O 模型变得轻量和高效, 非常适合 运行在分布式设备 的 数据密集型 的实时应用
这篇文章通过实例代码来给大家介绍如何利用 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)
- })
- })
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用 node.js 实现爬虫能有所帮助,如果有疑问大家可以留言交流。
来源: http://www.phperz.com/article/17/0510/331390.html