这2天看了下 nodeJs 的另外一种的爬虫方式,这个是利用 superagent 和 cheerio 的结合,这种方式与前面的【puppeteer爬虫】有所不同,puppeteer 可以达到模拟一个浏览器的效果。
而 superagent 和 cheerio 的实现思路是:
- 引入依赖
- 定义一个地址
- 发起请求
- 页面数据解析
- 分析页面数据
- 生成数据
实例:
import * as superagent from 'superagent';
import * as cheerio from 'cheerio';
import * as fs from 'fs';
import * as path from 'path';
/** * 处理空格和回车 * @param text * @returns {string} */
function replaceText(text) {
return text.replace(/\n/g, "").replace(/\s/g, "");
} const reptileUrl = 'http://www.jianshu.com';
const jsonDir = path.join(__dirname, 'json');
fs.exists(jsonDir) || fs.mkdir(jsonDir);
superagent.get(reptileUrl).end((error, res) => {
if (error) {
console.log(error);
}
/** * res.text 包含未解析前的响应内容 * 我们通过cheerio的load方法解析整个文档,就是html页面所有内容 */
let $ = cheerio.load(res.text);
// 可以通过console.log($.html());在控制台查看
// console.log($.html());
let data = [];
$('#list-container .note-list li').each((i, elem) => {
// 拿到当前li标签下所有的内容,开始干活了
let _this = $(elem);
// console.log('_this:',_this);
data.push({
id: _this.attr('data-note-id'),
slug: _this.find('.title').attr('href').replace(/\/p\//, ""),
author: {
slug: _this.find('.avatar').attr('href').replace(/\/u\//, ""),
avatar: _this.find('.avatar img').attr('src'), nickname: replaceText(_this.find('.blue-link').text()), sharedTime: _this.find('.time').attr('data-shared-at')
},
title: replaceText(_this.find('.title').text()),
abstract: replaceText(_this.find('.abstract').text()),
thumbnails: _this.find('.wrap-img img').attr('src'),
collection_tag: replaceText(_this.find('.collection-tag').text()),
reads_count: replaceText(_this.find('.ic-list-read').parent().text()) * 1,
comments_count: replaceText(_this.find('.ic-list-comments').parent().text()) * 1,
likes_count: replaceText(_this.find('.ic-list-like').parent().text()) * 1
});
});
// console.log(data);
// 写入数据, 文件不存在会自动创建
fs.writeFile(
`${jsonDir}/${Date.now()}.json`,
JSON.stringify({ status: 0, data: data }),
function (err) {
if (err) throw err;
console.log('写入完成');
});
});
具体的参考这篇文章
https://segmentfault.com/a/1190000009542336
https://www.jianshu.com/p/1432e0f29abd
转载请注明:隨習筆記 » NodeJs笔记:superagent 和 cheerio 爬虫