NodeJs Express 爬取百度新闻

爱被打了一巴掌 2023-10-18 16:23 353阅读 0赞

第一步:使用express创建reptile应用

express reptile

第二步:reptile应用依赖的第三方模块(superagent 和cheerio)

superagent:superagent是node里一个非常方便的、轻量的、渐进式的第三方客户端请求代理模块,用他来请求目标页面

cheerio:相当于node版的jQuery,用过jQuery的同学会非常容易上手。它主要是用来获取抓取到的页面元素和其中的数据信息

本地安装第三方模块(superagent 和cheerio)

cnpm install superagent

cnpm install cheerio

编辑package.json

  1. {
  2. "name": "reptile",
  3. "version": "0.0.0",
  4. "private": true,
  5. "scripts": {
  6. "start": "node ./bin/www"
  7. },
  8. "dependencies": {
  9. "cookie-parser": "~1.4.3",
  10. "debug": "~2.6.9",
  11. "express": "~4.16.0",
  12. "http-errors": "~1.6.2",
  13. "jade": "~1.11.0",
  14. "morgan": "~1.9.0",
  15. "superagent": "~4.1.0", #依赖superagent 模块
  16. "cheerio": "~1.0.0-rc.2" #依赖cheerio 模块
  17. }
  18. }

第三步:分析百度新闻首页的页面信息:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3V6aGl3ZW5nYW5n_size_16_color_FFFFFF_t_70

  1. F12打开Chrome的控制台,审查页面元素,
  2. 经过查看左侧“热点新闻”信息所在DOM的结构,
  3. 我们发现所有的“热点新闻”信息(包括新闻标题和新闻页面链接)
  4. 都在id为#pane-news的<div>下面<ul>下<li>下的<a>标签中。
  5. jQuery的选择器表示为:#pane-news ul li a

第四步、数据爬取

在reptile/routes/index.js文件中,使用用superagent和cheerio请求目标页面,获取整个新闻首页信息。

  1. var express = require('express');
  2. var router = express.Router();
  3. // 引入所需要的第三方包
  4. var superagent= require('superagent');
  5. // 引入所需要的第三方包
  6. var cheerio = require('cheerio');
  7. let hotNew = []; // 热点新闻
  8. /* GET home page. */
  9. router.get('/', function(req, res, next) {
  10. superagent.get('http://news.baidu.com/').end((err, res) => {
  11. if (err) {
  12. // 如果访问失败或者出错,会这行这里
  13. console.log(`热点新闻抓取失败 - ${err}`)
  14. } else {
  15. // 访问成功,请求http://news.baidu.com/页面所返回的数据会包含在res
  16. // 抓取热点新闻数据
  17. hotNew = getHotNews(res)
  18. hotNew.forEach(function(item) {
  19. console.log(item.title);
  20. console.log(item.href);
  21. });
  22. }
  23. });
  24. });
  25. /*
  26. 热点新闻抓取
  27. */
  28. let getHotNews = (res) => {
  29. let hotNews = [];
  30. // 访问成功,请求http://news.baidu.com/页面所返回的数据会包含在res.text中。
  31. /* 使用cheerio模块的cherrio.load()方法,将HTMLdocument作为参数传入函数
  32. 以后就可以使用类似jQuery的$(selectior)的方式来获取页面元素
  33. */
  34. let $ = cheerio.load(res.text);
  35. // 找到目标数据所在的页面元素,获取数据
  36. $('div#pane-news ul li a').each((idx, ele) => {
  37. // cherrio中$('selector').each()用来遍历所有匹配到的DOM元素
  38. // 参数idx是当前遍历的元素的索引,ele就是当前便利的DOM元素
  39. let news = {
  40. title: $(ele).text(), // 获取新闻标题
  41. href: $(ele).attr('href') // 获取新闻网页链接
  42. };
  43. hotNews.push(news) // 存入最终结果数组
  44. });
  45. return hotNews
  46. };
  47. module.exports = router;

第五步:reptile应用安装项目依赖模块和应用启动

cnpm install

cnpm start

爬虫访问地址:http://localhost:3000

控制台输出数据结果如下:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pob3V6aGl3ZW5nYW5n_size_16_color_FFFFFF_t_70 1

发表评论

表情:
评论列表 (有 0 条评论,353人围观)

还没有评论,来说两句吧...

相关阅读