要想體驗 Node.js 強大的異步特性谒麦,爬蟲的場景就比較適合蟆融。
目標(biāo)
- 使用 superagent 抓取網(wǎng)頁
- 使用 cheerio 分析網(wǎng)頁
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 一樣乌企。
當(dāng)在瀏覽器中訪問 http://localhost:3000/ 時,輸出 CNode(https://cnodejs.org/ ) 社區(qū)首頁的所有帖子標(biāo)題和鏈接以及作者成玫,以 json 的形式返回加酵。
輸出示例:
[
{
"author": "xinyu198736",
"title": "【杭州】Node Party 第二期,9月25日下午哭当,大搜車不見不散",
"href": "/topic/57e38330f7dea63b0e6ab912"
},
{
"author": "Samurais",
"title": "[ 北京]9月25日 NodeParty@科技寺猪腕,報名從速 !",
"href": "/topic/57de1b15b11d78e3659db5b0"
}
]
直接上代碼:
var express = require('express');
var superagent = require('superagent');
var cheerio = require('cheerio');
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);
}
var items = [];
// sres.text 里面存儲著網(wǎng)頁的 html 內(nèi)容,將它傳給 cheerio.load钦勘,習(xí)慣性地命名為 `$`
// 接下來就可以使用熟悉的 jquery 操作了
var $ = cheerio.load(sres.text);
$('#topic_list .cell').each(function(index, element) {
var $img = $(element).find('img');
var $topic = $(element).find('.topic_title');
items.push({
author: $img.attr('title'),
title: $topic.attr('title'),
href: $topic.attr('href')
});
});
res.send(items);
});
});
app.listen(3000, function() {
console.log('app is listening at port 3000');
});
OK陋葡,一個簡單的爬蟲就是這么簡單。在這里還沒有利用到 Node.js 的異步并發(fā)特性彻采。不過接下來的兩篇內(nèi)容都是關(guān)于異步控制的腐缤。