javascript - 类似于 Puppeteer 中的 document.ready() 的功能?

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

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

有:

page.waitForSelector(selector)

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

最佳答案

您可以使用 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'});

关于javascript - 类似于 Puppeteer 中的 document.ready() 的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53017788/

相关文章:

javascript - Mongoose findOne 内部循环

node.js - CSS 图像无法在 Heroku 上使用 AngularJS 显示

javascript - 如何找出 Javascript 中某个文件正在调用什么函数

google-chrome - devtools 时间中的空是什么意思?

javascript - 计算数组中的元素,并将它们添加到数组中的 2 个对象中

javascript - 如何在单击时更改文本框中文本的字体样式?

Javascript 对象属性作为 map 的键

node.js - 如何使用 Node.js 和 Request 库将文件附加到 Mailgun 的 API 的 POST 请求

google-chrome - Chrome 模拟设备位置

javascript - 使多个 html5-video 在 iOS5 上点击开始