close

目標

如前一篇實作的範例(使用cheerio 抓取蘋果日報的RSS資訊)

這裡接著要做的是讀取CNN的RSS資訊

一個中文的網站一個英文的網站來當練習,哈哈...

CNN的RSS連結為 http://edition.cnn.com/services/rss/

cnnRSS

實作

下面的程式碼可以取得CNN的每個種類的資訊以及他們的href連結

cnn.getTitleList = function(req, res) {
    request({
        uri: rssLink,
        headers: {
            'User-Agent': 'Mozilla/5.0'
        }   
    }, function(error, response, html) {
        if (!error && response.statusCode == 200) {
            var titleList = []; 
            var title;
            var $ = cheerio.load(html, {
                decodeEntities: true,
                xmlMode: true
            }); 
            $('image title').each(function(i, element) {
                console.log($(this).text());
                title = $(this).text();
            }); 
            $('item title').each(function(i, element) {
                console.log($(this).text());
                titleList.push({
                    title: $(this).text()
                }); 
            }); 
            res.json({
                rssTitle: title,
                titleList: titleList
            });
        } else {
            res.json({
                status: 'error',
                message: 'fail to request'
            });
        }
    });
}

這裡的程式碼的目的則依據給訂的RSS href,取得RSS的內容

CNN的RSS內容就可以直接使用cheerio來讀取,不需要像蘋果日報那樣改用htmlparser2來處理,相對簡單些

cnn.getRssList = function(req, res) {
    var rssList = [];
    request({
            uri: cnnURL,
            headers: {
                'User-Agent': 'Mozilla/5.0'
            }
        },  
        function(error, response, html) {
            if (!error && response.statusCode == 200) {
                var $ = cheerio.load(html);
                $('tr td.cnnRSS:first-child').each(function(i, element) {
                    var next = $(this).siblings('.cnnRSS').children();
                    rssList.push({
                        category: $(this).text(),
                        link: $(next).attr("href")
                    }); 
                }); 
                res.json(rssList);
            } else {
                res.statusCode = 404;
                res.json({
                    status: 'error',
                    message: 'fail to request'
                }); 
            }   
        }); 
};
arrow
arrow
    全站熱搜

    Perry Wu 發表在 痞客邦 留言(0) 人氣()