You need to enable JavaScript to run this app. Puppeteer批量遍历多链接时避免同时启动大量Chromium的方法
优惠活动
大模型
产品
解决方案
定价
更多

Puppeteer批量遍历多链接时避免同时启动大量Chromium的方法

问题根因

你当前的实现有两个核心设计缺陷,直接导致资源耗尽:

  • 每个爬取任务独立启动一个全新的Chromium进程,1000个任务对应1000个浏览器实例,单进程内存占用就会超过10G,必然崩溃
  • 裸for循环调用异步函数时,循环不会等待异步任务执行完成,会立刻把所有待爬链接全部提交,没有任何并发控制
标准实现方案

核心思路是两点:全局复用单Chromium实例,用固定并发池调度任务,资源消耗可以降到原来的5%以下,同时保持合理的爬取速度。

实现步骤

  • 全局初始化:启动一次Chromium实例,所有爬取任务复用这个实例,全部任务执行完成后再统一关闭
  • 单页面爬取逻辑:每个任务只负责新开/关闭单个标签页,不操作浏览器实例的生命周期
  • 并发控制:设定固定并发阈值(通常3-5个标签页即可,过高不会提速反而会拖慢),任务执行完成后自动从待爬列表补位,全程保持稳定的并发数
  • 异常兜底:给每个爬取任务加错误捕获,单个页面加载失败不影响整体流程

优化后参考代码

const puppeteer = require('puppeteer');
const Datastore = require('nedb');
const { promisify } = require('util');

const database = new Datastore('database.db');
// 将nedb回调式API转成可await的异步方法,避免异步时序问题
const insertAsync = promisify(database.insert).bind(database);
const loadAsync = promisify(database.loadDatabase).bind(database);

// 全局配置:根据自己电脑配置调整并发数
const CONCURRENCY_LIMIT = 3;
// 待爬取的球员ID范围
const ID_RANGE = [0, 1000];

// 单页爬取逻辑:接收全局browser实例,不重复启动浏览器
async function scrapePlayer(browser, playerId) {
  const url = `https://url.com/?id=${playerId}&section=Ratings`;
  const page = await browser.newPage();
  try {
    await page.goto(url, { waitUntil: 'domcontentloaded' });
    const attributes = [];

    // 爬取球员姓名
    const [name] = await page.$x('//*[@id="ctl00_ctl00_ctl00_Main_Main_name"]');
    const txt = await name.getProperty('innerText');
    attributes.push(await txt.jsonValue());

    // 爬取12项球员属性
    for (let i = 1; i < 13; i++) {
      const xpath = `//*[@id="ctl00_ctl00_ctl00_Main_Main_SectionTabBox"]/div/div/div/div[1]/table/tbody/tr[${i}]/td[2]`;
      const [element] = await page.$x(xpath);
      const val = await element.getProperty('innerText');
      attributes.push(await val.jsonValue());
    }

    // 构造球员对象并存库
    const player = {
      Name: attributes[0],
      Athleticism: attributes[1],
      Speed: attributes[2],
      Durability: attributes[3],
      Work_Ethic: attributes[4],
      Stamina: attributes[5],
      Strength: attributes[6],
      Blocking: attributes[7],
      Tackling: attributes[8],
      Hands: attributes[9],
      Game_Instinct: attributes[10],
      Elusiveness: attributes[11],
      Technique: attributes[12],
    };
    await insertAsync(player);
    console.log(`球员#${playerId}爬取完成`);
  } catch (err) {
    console.error(`球员#${playerId}爬取失败:${err.message}`);
  } finally {
    // 无论成功失败,都关闭页面释放资源
    await page.close();
  }
}

// 批量并发调度器
async function runScraper() {
  await loadAsync();
  const browser = await puppeteer.launch();
  let currentId = ID_RANGE[0];
  const endId = ID_RANGE[1];

  // 生成固定数量的并发任务组
  const runningTasks = Array(CONCURRENCY_LIMIT).fill(null).map(async () => {
    while (currentId <= endId) {
      const idToScrape = currentId++;
      await scrapePlayer(browser, idToScrape);
    }
  });

  // 等待所有任务完成
  await Promise.all(runningTasks);
  // 所有任务跑完后统一关闭浏览器
  await browser.close();
}

// 启动爬取流程
runScraper();

额外优化提示

  • 可以开启请求拦截,过滤掉图片、字体、样式表这类对爬取无用的资源,将页面加载速度提升30%以上,降低内存占用
  • 数据库里可以增加一个scraped标记,程序中断重启时自动跳过已经爬过的ID,不用从头重复爬取
  • 爬取间隔可以加100-200ms的随机等待,避免短时间请求过多被目标网站拦截

内容的提问来源于stack exchange,提问作者Zachary McArthur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 04:15:08