使用 async 控制并发数量

本文探讨如何在爬虫项目中利用 async 库实现并发限制,以提高爬取效率并避免对目标网站造成过大压力。通过设置并发数,确保多个请求能有序进行,同时减少了被目标网站封禁的风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const eventproxy = require('eventproxy')
const superagent = require('superagent')
const cheerio = require('cheerio')
const url = require('url')
const async = require('async')
const ep = new eventproxy()
const cnodeUrl = 'https://cnodejs.org'
const topicUrls = [];
superagent.get(cnodeUrl)
  .end(function (err, res) {
    if (err) {
      return console.error(error)
    }
    const topicUrls = [];
    const $ = cheerio.load(res.text);
    $('#topic_list .topic_title').each((index, item) => {
      const href = url.resolve(cnodeUrl, $(item).attr('href'))
      topicUrls.push(href)
    })
    console.log(topicUrls.length)
    let count = 0;
    async.mapLimit(topicUrls, 6, function (url, callback) {
      count++
      console.log(`现在的并发数${count}`)
      superagent.get(url)
        .end(function (err, res) {
          if (err) return console.log(`fetch faild ${err.status}`)
          count--
          callback(null, [url, res.text])
        })
    }, function (err, result) {
      if (err) return console.log(err)
      result = result.map(item => {
        const $ = cheerio.load(item[1]);
        return ({
          title:$('.topic_full_title').text().trim(),
          url:item[0],
          comment1:$('.reply_content').eq(0).text().trim(),
        })
      })
      console.log(result)
      console.log(result.length)
    })
  })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值