【问题标题】:Function similar to document.ready() in Puppeteer?类似于 Puppeteer 中的 document.ready() 的功能?
【发布时间】:2019-03-31 17:58:47
【问题描述】:

Puppeteer 中有类似document.ready() 的东西吗?

有:

page.waitForSelector(selector)

既然任何一个 HTML 页面上都有这么多同名选择器,那么这个函数怎么能确定正确的页面已经加载呢?这是一个简单的功能,但是在page.content()之前使用它时引起了很多错误。我不确定这个函数有什么遗漏。

【问题讨论】:

    标签: javascript node.js google-chrome-devtools puppeteer headless-browser


    【解决方案1】:

    您可以使用page.waitForNavigation() 替代jQuery 的document.ready() 函数:

    await page.waitForNavigation({waitUntil: 'load'});             // consider navigation to be finished when the load event is fired.
    await page.waitForNavigation({waitUntil: 'domcontentloaded'}); // consider navigation to be finished when the DOMContentLoaded event is fired.
    await page.waitForNavigation({waitUntil: 'networkidle0'});     // consider navigation to be finished when there are no more than 0 network connections for at least 500 ms.
    await page.waitForNavigation({waitUntil: 'networkidle2'});     // consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.
    

    或者,您可以使用page.goto() 中的waitUntil 选项等待文档加载:

    await page.goto('https://example.com/', {waitUntil: 'load'});
    await page.goto('https://example.com/', {waitUntil: 'domcontentloaded'});
    await page.goto('https://example.com/', {waitUntil: 'networkidle0'});
    await page.goto('https://example.com/', {waitUntil: 'networkidle2'});
    

    【讨论】:

    • page.waitForNavigation({waitUntil: 'load'}) 在执行 30 秒后导致错误。很奇怪! (node:12768) UnhandledPromiseRejectionWarning: TimeoutError: Navigation Timeout Exceeded: 30000ms exceeded at Promise.then (C:\d\code\js\wbot\node_modules\puppeteer\lib\FrameManager.js:1230:21) at <anonymous>
    • @user938363 您可以使用page.waitForNavigation({timeout: 60000, waitUntil: 'load'})page.setDefaultNavigationTimeout(60000) 增加超时限制。
    • 你好Grant Miller,奇怪的是page.waitForNavigation的行已经被执行,当错误弹出时它正在执行下面的do loop。在do loop 中有一行page.reload({waitUntil: 'load'})。但错误指向page.waitForNavigation 行。可能问题实际上是关于page.reload
    猜你喜欢
    • 2012-07-29
    • 2020-01-13
    • 2012-12-15
    • 2012-12-19
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    相关资源
    最近更新 更多