node crawler如何添加promise支持

2020-06-17 07:57:47易采站长站整理

背景

最近在组内做一些爬虫相关的工作,本来想自己简单造个轮子的,但是经网友推荐后,采用了node-crawler,用了一段时间过后,确实满足了我的绝大部分需求,但是其 api 却不支持 promise,而且我还需要一些同步爬取、同步处理的能力,如果不用 promise 的话,写法很不优雅,所以我就简单地给其封装了一层 promise api

现状

目前 node-crawler 的使用方式不支持 promise ,这里直接给出 npm 上的使用例子


const Crawler = require("crawler")

// 实例化
const c = new Crawler({
// ... 可以传入一些配置
callback : function (error, res, done) {
// 请求回调,实例化的时候传入的 callback 是作为默认 callback 的,后续每次抓取如果没有传入 callback,那么都会调用默认 callback
done();
}
})

// 爬取
c.queue([{
uri: 'http://parishackers.org/',
jQuery: false,

// The global callback won't be called
callback: function (error, res, done) {
if(error){
console.log(error);
}else{
console.log('Grabbed', res.body.length, 'bytes');
}
done();
}
}])

这样的回调方式对于多爬虫同步爬取很不友好

改造

理想使用方式:


const Crawler = require('crawler')

const c = new Crawler({
// 一些默认配置
})

c
.queue({
uri: 'xxx'
})
.then(res => {
// 抓取成功
})
.catch(err => {
// 抓取失败
})

改造方案:


// utils/crawler.js
const Crawler = require('crawler')
const defaultOptions = {
jQuery: false,
rateLimit: fetchRateLimit,
retries: 0,
timeout: fetchTimeout,
}

module.exports = class PromiseifyCrawler extends Crawler {
// namespace 是为了后续抓取结果统一上报时候进行区分
constructor(namespace = 'unknow', options = {}) {
if (typeof namespace === 'object') {
options = namespace
namespace = 'unknow'
}

options = merge({}, defaultOptions, options)

const cb = options.callback
options.callback = (err, res, done) => {
typeof cb === 'function' && cb(err, res, noop)
process.nextTick(done)
// 在这里可以自定义抓取成功还是失败
// 我这里直接设置的是如果 http code 不是 200 就视为错误
// 而且在这里也可以做一些抓取成功失败的统计
if (err || res.statusCode !== 200) {
if (!err) err = new Error(`${res.statusCode}-${res.statusMessage}`)
err.options = res.options
err.options.npolisReject(err)