標籤:css 應用 知識 auth sso 安裝 資料 http func
目標
建立一個 lesson3 項目,在其中編寫代碼。
當在瀏覽器中訪問 http://localhost:3000/ 時,輸出 CNode(https://cnodejs.org/ ) 社區首頁的所有文章標題和連結,以 json 的形式
知識點:
- 學習使用 superagent 抓取網頁
- 學習使用 cheerio 分析網頁
庫介紹:
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 --save PACKAGE_NAME
- 寫應用邏輯
安裝2個庫和express
nmp install --save expressnmp install --save superagentnmp install --save cheerio
var superagent = require(‘superagent‘);var express = require(‘express‘);var cheerio = require(‘cheerio‘);var app = express();app.get(‘/‘, function(req, res, next ) { superagent.get(‘https://cnodejs.org/‘) .end( function( err, sres ) { if (err){ return next(err); } var $ = cheerio.load(sres.text); var items = []; // sres.text 裡面儲存著網頁的 html 內容,將它傳給 cheerio.load 之後 // 就可以得到一個實現了 jquery 介面的變數,我們習慣性地將它命名為 `$` // 剩下就都是 jquery 的內容了 $(‘#topic_list .topic_title ‘).each(function(idx, element ){ var $element = $(element); items.push({ title: $element.attr(‘title‘), href: $element.attr(‘href‘) }); }); //new $(‘#topic_list .user_avatar ‘).each(function(idx, element) { var $element = $(element); items[idx][‘author‘] = $element.attr(‘href‘).split(‘/‘)[2] }); res.send(items); });});app.listen(3000, function (req, res) { console.log(‘app is running at port 3000‘);});
node.js 使用 superagent 與 cheerio 完成簡單爬蟲