【Nodejs篇五】Node js 使用 superagent 与 cheerio 完成简单爬虫
生活随笔
收集整理的這篇文章主要介紹了
【Nodejs篇五】Node js 使用 superagent 与 cheerio 完成简单爬虫
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目標
當在瀏覽器中訪問 http://localhost:3000/ 時,輸出 CNode(https://cnodejs.org/ ) 社區首頁的所有帖子標題和鏈接,以 json 的形式。
輸出示例:
[{"title": "【公告】發招聘帖的同學留意一下這里","href": "http://cnodejs.org/topic/541ed2d05e28155f24676a12"},{"title": "發布一款 Sublime Text 下的 JavaScript 語法高亮插件","href": "http://cnodejs.org/topic/54207e2efffeb6de3d61f68f"} ] 復制代碼介紹
superagent(http://visionmedia.github.io/superagent/ ) 是個 http 方面的庫,可以發起 get 或 post 請求。 cheerio(https://github.com/cheeriojs/cheerio ) 大家可以理解成一個 Node.js 版的 jquery,用來從網頁中以 css selector 取數據,使用方式跟 jquery 一樣一樣的。
還記得我們怎么新建一個項目嗎? - 新建一個文件夾,進去之后 npm init - 安裝依賴 npm install superagent cheerio express --save - 寫應用邏
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/ 的內容superagent.get('https://cnodejs.org/').end(function (err, sres) {// 常規的錯誤處理if (err) {return next(err);}// sres.text 里面存儲著網頁的 html 內容,將它傳給 cheerio.load 之后// 就可以得到一個實現了 jquery 接口的變量,我們習慣性地將它命名為 `$`// 剩下就都是 jquery 的內容了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('開啟端口監聽'); }); 復制代碼總結
以上是生活随笔為你收集整理的【Nodejs篇五】Node js 使用 superagent 与 cheerio 完成简单爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 甲骨文推出新的云服务 协助企业顺利迁移至
- 下一篇: asp.net中打印指定控件内容