NodeJs Express 爬取百度新闻

不点 阅读:680 2021-03-31 20:59:45 评论: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

{ 
  "name": "reptile", 
  "version": "0.0.0", 
  "private": true, 
  "scripts": { 
    "start": "node ./bin/www" 
  }, 
  "dependencies": { 
    "cookie-parser": "~1.4.3", 
    "debug": "~2.6.9", 
    "express": "~4.16.0", 
    "http-errors": "~1.6.2", 
    "jade": "~1.11.0", 
    "morgan": "~1.9.0", 
	"superagent": "~4.1.0", #依赖superagent 模块 
	"cheerio": "~1.0.0-rc.2" #依赖cheerio 模块 
  } 
} 

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

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

第四步、数据爬取

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

var express = require('express'); 
var router = express.Router(); 
// 引入所需要的第三方包 
var superagent= require('superagent'); 
// 引入所需要的第三方包 
var cheerio = require('cheerio'); 
let hotNew = [];                                // 热点新闻 
 
 
/* GET home page. */ 
router.get('/', function(req, res, next) { 
  superagent.get('http://news.baidu.com/').end((err, res) => { 
  if (err) { 
    // 如果访问失败或者出错,会这行这里 
    console.log(`热点新闻抓取失败 - ${err}`) 
  } else { 
   // 访问成功,请求http://news.baidu.com/页面所返回的数据会包含在res 
   // 抓取热点新闻数据 
   hotNew = getHotNews(res) 
   hotNew.forEach(function(item) { 
    console.log(item.title); 
	console.log(item.href); 
	}); 
  } 
	}); 
}); 
 
 
/* 
	热点新闻抓取 
*/ 
 
let getHotNews = (res) => { 
  let hotNews = []; 
  // 访问成功,请求http://news.baidu.com/页面所返回的数据会包含在res.text中。 
   
  /* 使用cheerio模块的cherrio.load()方法,将HTMLdocument作为参数传入函数 
     以后就可以使用类似jQuery的$(selectior)的方式来获取页面元素 
   */ 
  let $ = cheerio.load(res.text); 
 
  // 找到目标数据所在的页面元素,获取数据 
  $('div#pane-news ul li a').each((idx, ele) => { 
    // cherrio中$('selector').each()用来遍历所有匹配到的DOM元素 
    // 参数idx是当前遍历的元素的索引,ele就是当前便利的DOM元素 
    let news = { 
      title: $(ele).text(),        // 获取新闻标题 
      href: $(ele).attr('href')    // 获取新闻网页链接 
    }; 
    hotNews.push(news)              // 存入最终结果数组 
  }); 
  return hotNews 
}; 
 
module.exports = router; 

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

cnpm install

cnpm start

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

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

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号