目標(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"
}
]
介紹
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 一樣一樣的。
還記得我們怎么新建一個項目嗎蚯斯?
- 新建一個文件夾薄风,進(jìn)去之后 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)聽');
});