js抓取网页内容(node.js基础模块http、网页分析工具cherrio实现爬虫)

优采云 发布时间: 2022-01-19 12:16

  js抓取网页内容(node.js基础模块http、网页分析工具cherrio实现爬虫)

  本文文章主要介绍node.js的基础模块http以及网页分析工具cherrio实现爬虫的相关资料。文中的示例代码非常详细,具有一定的参考价值。有兴趣的朋友可以仅供参考

  一、前言

  据说是对爬虫的初步探索,但实际上并没有用到爬虫相关的第三方类库。主要使用node.js基础模块http和网页分析工具cherrio。使用http直接获取url路径对应的网页资源,然后使用cherrio进行分析。在这里我把自己学过的主要案例打了出来,加深理解。在编码的过程中,我第一次使用forEach遍历jq得到的对象,直接报错,因为jq没有对应的方法,只能调用js数组。

  二、知识点

  ①:superagent抓取web工具。我还没用过。

  ②:cherrio web分析工具,可以理解为服务端的jQuery,因为语法是一样的。

  效果图

  1、 爬取整个页面

  2、分析数据,提供的示例是案例实现的示例。

  爬虫初步探索源码分析

   var http=require('http'); var cheerio=require('cheerio'); var url='http://www.imooc.com/learn/348'; /**************************** 打印得到的数据结构 [{ chapterTitle:'', videos:[{ title:'', id:'' }] }] ********************************/ 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'); }) }); } /************* 分析从网页里抓取到的数据 **************/ function filterChapter(html){ var courseData=[]; var $=cheerio.load(html); var chapters=$('.chapter'); 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('.studyvideo'); var title=video.text(); var id=video.attr('href').split('/video')[1]; chapterData.videos.push({ title:title, id:id }) }) courseData.push(chapterData); }); return courseData; } http.get(url,function(res){ var html=''; res.on('data',function(data){ html+=data; }) res.on('end',function(){ var courseData=filterChapter(html); printCourseInfo(courseData); }) }).on('error',function(){ console.log('获取课程数据出错'); })

  参考:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线