Node.js抓数据(demo)


// 抓数据用的模块 http、https,这两个都是内置模块(核心模块)


// 1. 加载 https 模块
var https = require('https');

// 加载 cheerio 模块
var cheerio = require('cheerio');
var fs = require('fs');
var path = require('path');


// 2. 构建 options (构建请求信息:请求报文)
var options = {
  hostname: 'www.qiushibaike.com',
  port: 443,
  path: '/',
  method: 'GET',
  headers: {
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    'Upgrade-Insecure-Requests': '1',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6'
  }
};



// 3. 调用 https 的 request() 方法,向服务器发起请求,并且获取服务器返回的结果(页面代码)
// https.request(options[, callback])
var req = https.request(options, function (res) {
  // 通过监听 res 的 data 事件 和 end 事件获取服务器返回的数据

  var buffer = [];
  res.on('data', function (chunk) {
    // body...
    buffer.push(chunk);
  });

  res.on('end', function () {
    // body...
    buffer = Buffer.concat(buffer);
    var html = buffer.toString('utf8');
    // console.log(html);

    // 通过 cheerio 模块加载 HTML 代码 
    var $ = cheerio.load(html);


    var jokes = [];

    // 通过选择器选择我们要的元素
    // 1. 选取所有段子的div
    $('div.article.block.untagged.mb15').each(function (idx, ele) {
      // 提取段子作者
      var author = $(ele).find('h2').text();
      // console.log(author);
      // 提取段子正文
      var content = $(ele).find('div.content span').text();
      // console.log(content);

      // 把每个段子放到数组中
      jokes.push({
        author: author,
        content: content
      });
    });


    // 把 jokes 写入到文件
    fs.writeFile(path.join(__dirname, 'jokes.json'), JSON.stringify(jokes), function (err) {
      if (err) {
        throw err;
      }
      console.log('ok');
    });
  });
});


// 监听本次请求是否出错
req.on('error', function (err) {
  console.log('出错了:' + err);
});


// 如果是 post 请求要设置请求报文体
// req.write(postData);

// 结束本次请求
// 表示客户端向服务器发送的数据都发完了
req.end();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值