// 抓数据用的模块 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();
Node.js抓数据(demo)
最新推荐文章于 2024-09-08 13:38:16 发布