Node 简单爬虫
来源:互联网 发布:pinnacle软件 编辑:程序博客网 时间:2024/05/21 06:34
以爬慕课网Hadoop进阶课程为例,用Node写一个简单的爬虫:
先抓取这个网站的源码:
var http = require('http');var url = 'http://www.imooc.com/learn/890';http.get(url, function(res) { var html = ''; res.on('data', function(data) { html += data; }) res.on('end', function() { console.log(html); })}).on('error', function() { console.log('获取课程数据出错!')})
然后分析这个页面的Dom,如图:
每大章节都被一个chapter包围,抓取下来就是一个数组,对每个item,这张的大标题在strong里面,每章的小章节在video标签里,然后小标题就是J-media-item的text,id就用video的编号,字符串截取下来。
代码:
var http = require('http');var cheerio = require('cheerio')var url = 'http://www.imooc.com/learn/890';function filterChapters(html) { var $ = cheerio.load(html) var chapters = $('.chapter') // [{ // chapterTitle: "", // videos: [ // title: "", // id: "" // ] // }] var courseData = [] 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('.J-media-item') var videoTitle = video.text() var id = video.attr('href').split('video/')[1] chapterData.videos.push({ title: videoTitle, id: id }) }) courseData.push(chapterData) }) return courseData}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'); }) })}http.get(url, function(res) { var html = ''; res.on('data', function(data) { html += data; }) res.on('end', function() { var courseData = filterChapters(html) printCourseInfo(courseData) })}).on('error', function() { console.log('获取课程数据出错!')})
当然爬下来的结果格式有点杂乱无章:
可以在加点代码格式化一下,也可以用IO写进磁盘文件。
阅读全文
0 0
- Node.JS 简单爬虫
- Node 简单爬虫
- node 简单爬虫
- node js简单爬虫实现
- Node.js 笔记四: 简单爬虫
- Node.js简单爬虫开发过程
- node爬虫
- node.js实现简单的网络爬虫程序
- 简单的node爬虫练手,循环中的异步转同步
- 用node从零开始去写一个简单的爬虫
- 轮子:一个简单的node爬虫踩坑之路
- Node.js 实现爬虫(1) —— 简单的爬虫程序
- node.js爬虫01
- node.js爬虫03
- node.js 小爬虫
- node js 小爬虫
- Node.js爬虫技术
- 简单爬虫
- JMeter插件之 BlazeMeter's XMPP----测试Openfire等
- ElasticSearch的增、删、改、查操作
- 07-端口无法访问的问题
- activeMQ+Spring-mvc结合使用
- 百度OCR api 的python 调用
- Node 简单爬虫
- 互联网程序猿快来看
- Linux的单用户模式
- malloc-解析(嵌入式)
- C#中的类
- 批处理bat 延时启动的方法
- 三种更改hostname的方法之间的对比
- HDU 3333 Turing Tree(线段树)
- linux下安装运行LoadrGenerator