木偶师有时会扔"UnhandledPromiseRejectionWarning: TimeoutError: Navigation Timeout Exceeded"



我正在用木偶测试无头铬,所以我已经阅读文档并运行此代码*:

const puppeteer = require('puppeteer');
(async() => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://www.github.com', {waitUntil: 'networkidle2'});
    await page.screenshot({ path: 'screenshot.png' });
    await browser.close();
})();

(*docs-usage的摘要(。

我更改了" example.com",因为正常工作并与其他网站一起尝试,但是使用" github.com"脚本返回 await page.goto()行中的超时例外:

(node:7840) UnhandledPromiseRejectionWarning: TimeoutError: Navigation Timeout Exceeded: 30000ms exceeded
    at Promise.then (C:_testheadlessnode_modulespuppeteerlibLifecycleWatcher.js:142:21)
    at <anonymous>
  -- ASYNC --
    at Frame.<anonymous> (C:_testheadlessnode_modulespuppeteerlibhelper.js:111:15)
    at Page.goto (C:_testheadlessnode_modulespuppeteerlibPage.js:629:49)
    at Page.<anonymous> (C:_testheadlessnode_modulespuppeteerlibhelper.js:112:23)
    at C:_testheadlessindex.js:7:16
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
(node:7840) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7840) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

如果我使用常规浏览器访问GitHub.com,则在正常的时机中进行连接,因此我的互联网连接不是问题。

我已经添加了下一行,并且在两分钟之后,代码运行正常

page.setDefaultNavigationTimeout(0);

但是,如果我设置puppeteer.launch({headless:false}),则代码在短短几秒钟内运行完美

我正在运行我的测试:

  • Windows 7专业SP1
  • 节点8.11.1
  • Puppeteer 1.18.0
  • Puppeteer Core 1.18.0

我遇到了相同的问题,但通过替换

解决了它
{waitUntil: 'networkidle2'}

with:

{waitUntil: 'domcontentloaded'}

更多信息在这里:

[https://github.com/puppeteer/puppeteer/issues/2482] [1]

只是为了添加更多信息,有些站点有很多内容,因此该页面可能在30秒的默认超时内加载了。因此,请放弃此操作,您可以完全删除超时:

await page.setDefaultNavigationTimeout(0)

这样看起来可以这样:

const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.setDefaultNavigationTimeout(0);
await page.goto('https://www.example.com/', {
waitUntil: 'networkidle2'
});

有时服务器不响应无头请求(puppeteer#2963(。
要验证这一点,我将尝试以调试模式运行代码:

DEBUG=*session node your-test-file.js

最新更新