类似于 Puppeteer 中的 document.ready() 的功能?
Function similar to document.ready() in Puppeteer?
Puppeteer
中是否有类似document.ready()
的内容?
有:
page.waitForSelector(selector)
既然任何一个HTML页面上都有那么多同名选择器,这个函数怎么能确定加载了正确的页面呢?这是一个简单的功能,但我在 page.content()
之前使用它时导致了很多错误。我不确定这个功能遗漏了什么。
您可以使用page.waitForNavigation()
as an alternative to jQuery's 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'});
有时 waitForNavigation 只是超时。我想出了使用 waitForFunction 的其他解决方案,检查文档是否处于就绪状态。
await page.waitForFunction(() => document.readyState === "complete");
Puppeteer
中是否有类似document.ready()
的内容?
有:
page.waitForSelector(selector)
既然任何一个HTML页面上都有那么多同名选择器,这个函数怎么能确定加载了正确的页面呢?这是一个简单的功能,但我在 page.content()
之前使用它时导致了很多错误。我不确定这个功能遗漏了什么。
您可以使用page.waitForNavigation()
as an alternative to jQuery's 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'});
有时 waitForNavigation 只是超时。我想出了使用 waitForFunction 的其他解决方案,检查文档是否处于就绪状态。
await page.waitForFunction(() => document.readyState === "complete");