本文共 2073 字,大约阅读时间需要 6 分钟。
爬虫是网络世界中的“探索者”,通过抓取网页代码获取各种数据。Node.js 生态中,利用 http 模块可以轻松实现简单的爬虫功能。
var http = require('http');var url = "http://www.imooc.com/learn/348";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('请求出错');}); 将代码保存为 imooc-crawler.js,运行命令:
node imooc-crawler.js
注意:确保脚本路径正确。
为了更好地抓取结构化数据,我们需要 cheerio 库,它类似于 jQuery,支持 DOM 操作。
安装依赖:
npm install cheerio
完成后,修改爬虫代码:
var http = require('http');var cheerio = require('cheerio');var url = "http://www.imooc.com/learn/348";function filterChapters(html) { var $ = cheerio.load(html); var courseData = []; $('.learnchapter').each(function(item) { var chapter = $(this); var chapterTitle = chapter.find('strong').text(); var videos = chapter.find('.video').children('li'); var chapterData = { title: chapterTitle, videos: [] }; videos.each(function(item) { var video = $(this).find('.studyvideo'); 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) { console.log(item.title); item.videos.forEach(function(video) { console.log(' [' + video.id + '] ' + video.title); }); });}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('请求出错');}); 将代码保存为 crawler.js,运行命令:
node crawler.js
本次实践主要体验了 Node.js 爬虫开发的基础流程。通过 cheerio 学习了如何操作 DOM 结构,掌握了爬取网页内容的基础方法。
转载地址:http://xvjfk.baihongyu.com/