我的环境
我的问题是:
我有一个for...of
循环,可以使用伪造者访问3000多个URL。我使用puppeteer.connect
到wsEndpoint
来重用一个浏览器实例。每次访问后我都会断开连接并关闭标签。
page.goto
立即打开网址,page.goto
的每个网址使用2-3次重试,page.goto
以上,每个网址使用5-8次重试,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'
}
答案 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()
[...]