博客
关于我
nodejs http小爬虫
阅读量:795 次
发布时间:2023-02-16

本文共 2073 字,大约阅读时间需要 6 分钟。

Node.js 小爬虫实践

爬虫是网络世界中的“探索者”,通过抓取网页代码获取各种数据。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/

你可能感兴趣的文章
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>