博客
关于我
nodejs http小爬虫
阅读量:796 次
发布时间: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/

你可能感兴趣的文章
Nginx 学习总结(16)—— 动静分离、压缩、缓存、黑白名单、性能等内容温习
查看>>
Nginx 学习总结(17)—— 8 个免费开源 Nginx 管理系统,轻松管理 Nginx 站点配置
查看>>
Nginx 学习(一):Nginx 下载和启动
查看>>
nginx 常用指令配置总结
查看>>
Nginx 常用配置清单
查看>>
nginx 常用配置记录
查看>>
nginx 开启ssl模块 [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx
查看>>
Nginx 我们必须知道的那些事
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置清单(一篇够用)
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>