用Nodejs实现一个简单的爬虫功能。(ES6标准)

Nodejs版本:v10.11.0

依赖模块:express,superagent,cheerio

代码:

const express = require('express');
const superagent = require('superagent');
const cheerio = require('cheerio');

const app = express();

app.get('/', function (req, res, next) { 
  superagent.get('https://cnodejs.org/')
    .end(function (err, sres) {    
      if (err) {
        return next(err);
      }

      const $ = cheerio.load(sres.text);
      let items = [];
     
      $('#topic_list .cell').each(function (idx, element) {          
      const $element = $(element).find('.topic_title').eq(0);
      const $author = $(element).find('.user_avatar img').eq(0);
      items.push({
          title: $element.attr('title'),
          href: $element.attr('href'),
          author: $author.attr('title')
      });
      });
          
      res.send(items);
    });
});

app.listen(3000, function(req,res){
    console.log('app is running at port 3000');
})

猜你喜欢

转载自blog.csdn.net/scyu/article/details/82952811
今日推荐