node.js 使用 superagent 與 cheerio 完成簡單爬蟲

來源:互聯網
上載者:User

標籤:css   應用   知識   auth   sso   安裝   資料   http   func   

目標

建立一個 lesson3 項目,在其中編寫代碼。

當在瀏覽器中訪問 http://localhost:3000/ 時,輸出 CNode(https://cnodejs.org/ ) 社區首頁的所有文章標題和連結,以 json 的形式

 

知識點:

  1. 學習使用 superagent 抓取網頁
  2. 學習使用 cheerio 分析網頁

 

庫介紹:

superagent(http://visionmedia.github.io/superagent/ ) 是個 http 方面的庫,可以發起 get 或 post 請求。

cheerio(https://github.com/cheeriojs/cheerio ) 大家可以理解成一個 Node.js 版的 jquery,用來從網頁中以 css selector 取資料,使用方式跟 jquery 一樣一樣的。

建立項目相關命令:

  1. 建立一個檔案夾,進去之後 npm init
  2. 安裝依賴 npm install --save PACKAGE_NAME
  3. 寫應用邏輯

安裝2個庫和express

nmp install --save expressnmp install --save superagentnmp install --save cheerio

 

 

var superagent = require(‘superagent‘);var express = require(‘express‘);var cheerio = require(‘cheerio‘);var app = express();app.get(‘/‘, function(req, res, next ) {    superagent.get(‘https://cnodejs.org/‘)        .end( function( err, sres ) {            if (err){                return next(err);            }            var $ = cheerio.load(sres.text);            var items = [];               // sres.text 裡面儲存著網頁的 html 內容,將它傳給 cheerio.load 之後               // 就可以得到一個實現了 jquery 介面的變數,我們習慣性地將它命名為 `$`              // 剩下就都是 jquery 的內容了            $(‘#topic_list .topic_title ‘).each(function(idx, element ){                var $element = $(element);                items.push({                    title: $element.attr(‘title‘),                    href: $element.attr(‘href‘)                });            });            //new             $(‘#topic_list .user_avatar ‘).each(function(idx, element) {                var $element = $(element);                items[idx][‘author‘] = $element.attr(‘href‘).split(‘/‘)[2]            });            res.send(items);        });});app.listen(3000, function (req, res) {  console.log(‘app is running at port 3000‘);});

 

node.js 使用 superagent 與 cheerio 完成簡單爬蟲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.