【Nodejs篇五】Node js 使用 superagent 与 cheerio 完成简单爬虫
生活随笔
收集整理的這篇文章主要介紹了
【Nodejs篇五】Node js 使用 superagent 与 cheerio 完成简单爬虫
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
目標(biāo)
當(dāng)在瀏覽器中訪問 http://localhost:3000/ 時,輸出 CNode(https://cnodejs.org/ ) 社區(qū)首頁的所有帖子標(biāo)題和鏈接,以 json 的形式。
輸出示例:
[{"title": "【公告】發(fā)招聘帖的同學(xué)留意一下這里","href": "http://cnodejs.org/topic/541ed2d05e28155f24676a12"},{"title": "發(fā)布一款 Sublime Text 下的 JavaScript 語法高亮插件","href": "http://cnodejs.org/topic/54207e2efffeb6de3d61f68f"} ] 復(fù)制代碼介紹
superagent(http://visionmedia.github.io/superagent/ ) 是個 http 方面的庫,可以發(fā)起 get 或 post 請求。 cheerio(https://github.com/cheeriojs/cheerio ) 大家可以理解成一個 Node.js 版的 jquery,用來從網(wǎng)頁中以 css selector 取數(shù)據(jù),使用方式跟 jquery 一樣一樣的。
還記得我們怎么新建一個項目嗎? - 新建一個文件夾,進去之后 npm init - 安裝依賴 npm install superagent cheerio express --save - 寫應(yīng)用邏
eg:
const superagent = require('superagent'); const cheerio = require('cheerio'); const express = require('express'); var app = express();app.get('/', function (req, res, next) {// 用 superagent 去抓取 https://cnodejs.org/ 的內(nèi)容superagent.get('https://cnodejs.org/').end(function (err, sres) {// 常規(guī)的錯誤處理if (err) {return next(err);}// sres.text 里面存儲著網(wǎng)頁的 html 內(nèi)容,將它傳給 cheerio.load 之后// 就可以得到一個實現(xiàn)了 jquery 接口的變量,我們習(xí)慣性地將它命名為 `$`// 剩下就都是 jquery 的內(nèi)容了var $ = cheerio.load(sres.text);var items = [];$('#topic_list .topic_title').each(function (idx, element) {var $element = $(element);items.push({title: $element.attr('title'),href: $element.attr('href')});});res.send(items);}); });app.listen(3000,function() {console.log('開啟端口監(jiān)聽'); }); 復(fù)制代碼總結(jié)
以上是生活随笔為你收集整理的【Nodejs篇五】Node js 使用 superagent 与 cheerio 完成简单爬虫的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 甲骨文推出新的云服务 协助企业顺利迁移至
- 下一篇: Django REST框架 -1