使用 superagent 與 cheerio 完成簡單爬蟲

要想體驗(yàn) Node.js 強(qiáng)大的異步特性,爬蟲的場(chǎng)景就比較適合。

目標(biāo)
  • 使用 superagent 抓取網(wǎng)頁
  • 使用 cheerio 分析網(wǎng)頁

superagent(http://visionmedia.github.io/superagent/ ) 是個(gè) http 方面的庫,可以發(fā)起 get 或 post 請(qǐng)求。

cheerio(https://github.com/cheeriojs/cheerio ) 可以理解成一個(gè) Node.js 版的 jQuery,用來從網(wǎng)頁中以 css selector 取數(shù)據(jù),使用方式跟 jQuery 一樣。

當(dāng)在瀏覽器中訪問 http://localhost:3000/ 時(shí),輸出 CNode(https://cnodejs.org/ ) 社區(qū)首頁的所有帖子標(biāo)題和鏈接以及作者,以 json 的形式返回。
輸出示例:

[
    {
        "author": "xinyu198736",
        "title": "【杭州】Node Party 第二期,9月25日下午,大搜車不見不散",
        "href": "/topic/57e38330f7dea63b0e6ab912"
    },
    {
        "author": "Samurais",
        "title": "[ 北京]9月25日 NodeParty@科技寺,報(bào)名從速 !",
        "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ī)的錯(cuò)誤處理
            if (err) {
                return next(err);
            }
            var items = [];
            // sres.text 里面存儲(chǔ)著網(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,一個(gè)簡單的爬蟲就是這么簡單。在這里還沒有利用到 Node.js 的異步并發(fā)特性。不過接下來的兩篇內(nèi)容都是關(guān)于異步控制的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容