当前位置:Gxlcms > JavaScript > node实现爬虫功能案例分析

node实现爬虫功能案例分析

时间:2021-07-01 10:21:17 帮助过:20人阅读

这次给大家带来node实现爬虫功能案例分析,node实现爬虫功能的注意事项有哪些,下面就是实战案例,一起来看一下。

node是服务器端的语言,所以可以像python一样对网站进行爬取,下面就使用node对博客园进行爬取,得到其中所有的章节信息。

第一步: 建立crawl文件,然后npm init。

第二步: 建立crawl.js文件,一个简单的爬取整个页面的代码如下所示:

  1. var http = require("http");
  2. var url = "http://www.cnblogs.com";
  3. http.get(url, function (res) {
  4. var html = "";
  5. res.on("data", function (data) {
  6. html += data;
  7. });
  8. res.on("end", function () {
  9. console.log(html);
  10. });
  11. }).on("error", function () {
  12. console.log("获取课程结果错误!");
  13. });

即引入http模块,然后利用http对象的get请求,即一旦运行,相当于node服务器端发送了一个get请求请求这个页面,然后通过res返回,其中on绑定data事件用来不断地接受数据,最后end时我们就在后台打印出来。

这只是整个页面的一部分,我们可以在此页面审查元素,发现确实是一样的

我们只需要将其中的章节title和每一小节的信息爬到即可。

第三步: 引入cheerio模块,如下:(在gitbash中安装即可,cmd总是出问题)

  1. cnpm install cheerio --save-dev

这个模块的引入,就是为了方便我们操作dom,就像jQuery一样。

第四步: 操作dom,获取有用信息。

  1. var http = require("http");
  2. var cheerio = require("cheerio");
  3. var url = "http://www.cnblogs.com";
  4. function filterData(html) {
  5. var $ = cheerio.load(html);
  6. var items = $(".post_item");
  7. var result = [];
  8. items.each(function (item) {
  9. var tit = $(this).find(".titlelnk").text();
  10. var aut = $(this).find(".lightblue").text();
  11. var one = {
  12. title: tit,
  13. author: aut
  14. };
  15. result.push(one);
  16. });
  17. return result;
  18. }
  19. function printInfos(allInfos) {
  20. allInfos.forEach(function (item) {
  21. console.log("文章题目 " + item["title"] + '\n' + "文章作者 " + item["author"] + '\n'+ '\n');
  22. });
  23. }
  24. http.get(url, function (res) {
  25. var html = "";
  26. res.on("data", function (data) {
  27. html += data;
  28. });
  29. res.on("end", function (data) {
  30. var allInfos = filterData(html);
  31. printInfos(allInfos);
  32. });
  33. }).on("error", function () {
  34. console.log("爬取博客园首页失败")
  35. });

即上面的过程就是在爬取博客的题目和作者。

最终后台输出如下:

这和博客园首页的内容是一致的:

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

Vue.js计算与侦听器属性使用详解

js三种调用方式优缺点总结

以上就是node实现爬虫功能案例分析的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行