## 目標
建立一個 lesson3 項目,在其中編寫代碼。
當在瀏覽器中訪問?`http://localhost:3000/`?時,輸出 CNode([https://cnodejs.org/](https://cnodejs.org/)?) 社區首頁的所有帖子標題和鏈接,以 json 的形式。
輸出示例:
~~~
[
{
"title": "【公告】發招聘帖的同學留意一下這里",
"href": "http://cnodejs.org/topic/541ed2d05e28155f24676a12"
},
{
"title": "發布一款 Sublime Text 下的 JavaScript 語法高亮插件",
"href": "http://cnodejs.org/topic/54207e2efffeb6de3d61f68f"
}
]
~~~
## [](https://github.com/alsotang/node-lessons/tree/master/lesson3#挑戰)挑戰
訪問?`http://localhost:3000/`?時,輸出包括主題的作者,
示例:
~~~
[
{
"title": "【公告】發招聘帖的同學留意一下這里",
"href": "http://cnodejs.org/topic/541ed2d05e28155f24676a12",
"author": "alsotang"
},
{
"title": "發布一款 Sublime Text 下的 JavaScript 語法高亮插件",
"href": "http://cnodejs.org/topic/54207e2efffeb6de3d61f68f",
"author": "otheruser"
}
]
~~~
## [](https://github.com/alsotang/node-lessons/tree/master/lesson3#知識點)知識點
1. 學習使用 superagent 抓取網頁
2. 學習使用 cheerio 分析網頁
## [](https://github.com/alsotang/node-lessons/tree/master/lesson3#課程內容)課程內容
Node.js 總是吹牛逼說自己異步特性多么多么厲害,但是對于初學者來說,要找一個能好好利用異步的場景不容易。我想來想去,爬蟲的場景就比較適合,沒事就異步并發地爬幾個網站玩玩。
本來想教大家怎么爬 github 的 api 的,但是 github 有 rate limit 的限制,所以只好犧牲一下 CNode 社區(國內最專業的 Node.js 開源技術社區),教大家怎么去爬它了。
我們這回需要用到三個依賴,分別是 express,superagent 和 cheerio。
先介紹一下,
superagent([http://visionmedia.github.io/superagent/](http://visionmedia.github.io/superagent/)?) 是個 http 方面的庫,可以發起 get 或 post 請求。
cheerio([https://github.com/cheeriojs/cheerio](https://github.com/cheeriojs/cheerio)?) 大家可以理解成一個 Node.js 版的 jquery,用來從網頁中以 css selector 取數據,使用方式跟 jquery 一樣一樣的。
還記得我們怎么新建一個項目嗎?
1. 新建一個文件夾,進去之后?`npm init`
2. 安裝依賴?`npm install --save PACKAGE_NAME`
3. 寫應用邏輯
我們應用的核心邏輯長這樣
~~~
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);
});
});
~~~
OK,一個簡單的爬蟲就是這么簡單。這里我們還沒有利用到 Node.js 的異步并發特性。不過下兩章內容都是關于異步控制的。
記得好好看看 superagent 的 API,它把鏈式調用的風格玩到了極致。
- 關于
- Lesson 0: 《搭建 Node.js 開發環境》
- Lesson 1: 《一個最簡單的 express 應用》
- Lesson 2: 《學習使用外部模塊》
- Lesson 3: 《使用 superagent 與 cheerio 完成簡單爬蟲》
- Lesson 4: 《使用 eventproxy 控制并發》
- Lesson 5: 《使用 async 控制并發》
- Lesson 6: 《測試用例:mocha,should,istanbul》
- Lesson 7: 《瀏覽器端測試:mocha,chai,phantomjs》
- Lesson 8: 《測試用例:supertest》
- Lesson 9: 《正則表達式》
- Lesson 10: 《benchmark 怎么寫》
- Lesson 11: 《作用域與閉包:this,var,(function () {})》
- Lesson 12: 《線上部署:heroku》
- Lesson 13: 《持續集成平臺:travis》
- Lesson 14: 《js 中的那些最佳實踐》
- Lesson 15: 《Mongodb 與 Mongoose 的使用》
- Lesson 16: 《cookie 與 session》
- Lesson 17: 《使用 promise 替代回調函數》