类似于Puppeteer中的document.ready()的函数?

问题描述 投票:0回答:2

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

有:

page.waitForSelector(selector)

既然任何 HTML 页面上都有如此多的同名选择器,那么这个函数如何确定正确的页面已被加载呢?这是一个简单的功能,但是我之前使用它时出现了很多错误

page.content()
。我不确定这个功能错过了什么。

javascript node.js google-chrome-devtools puppeteer headless-browser
2个回答
23
投票

您可以使用

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.

或者,您可以使用

waitUntil
 中的 
page.goto()
选项来等待文档加载:

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

1
投票

有时 waitForNavigation 只是超时。我想出了使用 waitForFunction 的其他解决方案,检查文档是否处于就绪状态。

await page.waitForFunction(() => document.readyState === "complete");
© www.soinside.com 2019 - 2024. All rights reserved.