首页 > 解决方案 > Puppeteer:在 browser.disconnect 之后,Chromium 实例在后台保持活动状态

问题描述

我的环境

我的问题是:

我有一个for...of循环可以使用 puppeteer 访问 3000 多个网址。我习惯puppeteer.connect了,wsEndpoint所以我可以重用一个浏览器实例。每次访问后我都会断开连接并关闭选项卡。

我检查了 Windows 任务管理器,发现有数百个 Chromium 实例在后台运行,每个实例使用 80-90MB 的内存和 1-2% 的 CPU。

问题

我怎样才能真正杀死我已经断开连接的 Chromium 实例browser.disconnect

示例脚本

const puppeteer = require('puppeteer')
const urlArray = require('./urls.json') // contains 3000+ urls in an array


async function fn() {
  const browser = await puppeteer.launch({ headless: true })
  const browserWSEndpoint = await browser.wsEndpoint()

  for (const url of urlArray) {
    try {
      const browser2 = await puppeteer.connect({ browserWSEndpoint })
      const page = await browser2.newPage()
      await page.goto(url) // in my original code it's also wrapped in a retry function

      // doing cool things with the DOM

      await page.goto('about:blank') // because of you: https://github.com/puppeteer/puppeteer/issues/1490
      await page.close()
      await browser2.disconnect()
    } catch (e) {
      console.error(e)
    }
  }
  await browser.close()
}
fn()

错误

通常的 puppeteer 超时错误。

TimeoutError: Navigation timeout of 30000 ms exceeded
    at C:\[...]\node_modules\puppeteer\lib\LifecycleWatcher.js:100:111
  -- ASYNC --
    at Frame.<anonymous> (C:\[...]\node_modules\puppeteer\lib\helper.js:94:19)
    at Page.goto (C:\[...]\node_modules\puppeteer\lib\Page.js:476:53)
    at Page.<anonymous> (C:\[...]\node_modules\puppeteer\lib\helper.js:95:27)
    at example (C:\[...]\example.js:13:18)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  name: 'TimeoutError'
}

标签: puppeteerchromium

解决方案


最后,我能够通过在启动时添加--single-process--no-zygoteargs 来达到预期的结果(--no-sandbox它们需要 +)。

正在运行的 Chromium 进程的数量不再呈指数增长,但只有两个实例保持活动状态:其中一个是第一个位置的通常空选项卡,第二个被puppeteer.connect({ browserWSEndpoint }).

[...]
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--single-process', '--no-zygote', '--no-sandbox']
  })
  const browserWSEndpoint = await browser.wsEndpoint()
[...]
  • --single-process:在与浏览器相同的进程中运行渲染器和插件[来源]

  • --no-zygote: Disables the use of a zygote process for forking child processes. Instead, child processes will be forked and exec'd directly. Note that --no-sandbox should also be used together with this flag because the sandbox needs the zygote to work. [source]


推荐阅读