'Function similar to document.ready() in Puppeteer?
Is there something like document.ready() in Puppeteer?
There is:
page.waitForSelector(selector)
Since there are so many same-name selector on any HTML page, how can this function can be sure that the right page has been loaded? It is a simple function, but caused quite a few errors when I use it before page.content(). I'm not sure what is missed about this function.
Solution 1:[1]
You can use page.waitForNavigation() as an alternative to jQuery's document.ready() function:
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.
Alternatively, you can use the waitUntil option in page.goto() to wait for the document to load:
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'});
Solution 2:[2]
Sometimes waitForNavigation just timeout. I came up with other solution using the waitForFunction, checking if document is in ready state.
await page.waitForFunction(() => document.readyState === "complete");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Grant Miller |
| Solution 2 | Yuri Olive |
