the*_*ton 7 chromium puppeteer
我的环境
我的问题是:
我有一个for...of循环可以使用 puppeteer 访问 3000 多个 url。我使用puppeteer.connect到wsEndpoint,所以我可以重复使用一个浏览器实例。每次访问后我都会断开连接并关闭选项卡。
page.goto网址立即打开网址,page.goto使用每个 url 2-3 次重试,page.goto使用每个 url 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()
Run Code Online (Sandbox Code Playgroud)
错误
通常的 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'
}
Run Code Online (Sandbox Code Playgroud)
the*_*ton 17
最后,我能够通过在启动时添加--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()
[...]
Run Code Online (Sandbox Code Playgroud)
--single-process:在与浏览器相同的进程中运行渲染器和插件[来源]
--no-zygote:禁止使用 zygote 进程来分叉子进程。相反,子进程将被直接分叉和执行。请注意, --no-sandbox 也应与此标志一起使用,因为沙箱需要 zygote 才能工作。[来源]
| 归档时间: |
|
| 查看次数: |
4333 次 |
| 最近记录: |