木偶:浏览器断开后,Chromium实例在后台仍处于活动状态

时间:2020-06-05 17:19:17

标签: puppeteer chromium

我的环境

  • 木偶版本:3.1.0
  • 平台/操作系统版本:Windows 10
  • Node.js版本:12.16.1

我的问题是:

我有一个for...of循环,可以使用伪造者访问3000多个URL。我使用puppeteer.connectwsEndpoint来重用一个浏览器实例。每次访问后我都会断开连接并关闭标签。

  • 前100个网址page.goto立即打开网址,
  • 高于100 page.goto的每个网址使用2-3次重试,
  • 在300 page.goto以上,每个网址使用5-8次重试,
  • 500以上时,我一直得到TimeoutError: Navigation timeout of 30000 ms exceeded

我检查了Windows任务管理器,并意识到数百个Chromium实例在后台运行,并且每个实例使用80-90MB的内存以及1-2%的CPU。

问题

如何真正终止与browser.disconnect断开连接的Chromium实例?

示例脚本

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()

错误

通常的操纵up超时错误。

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'
}

1 个答案:

答案 0 :(得分:4)

最后,我能够通过在启动时添加--single-process--no-zygote args来获得期望的结果(它们需要+ --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:以与浏览器[source]

  • 相同的过程运行渲染器和插件
  • --no-zygote:禁止使用合子进程派生子进程。相反,子进程将被直接派生并执行。请注意,--no-sandbox也应与此标志一起使用,因为沙箱需要合子才能工作。 [source]