Puppeteer页面请求waitUntil、waitfor、setDefaultTimeout
Author:zhoulujun Date:
waitUntil
全局等待: 作用于整个页面加载过程,而不是单个元素。
await page.goto('https://example.com', { waitUntil: 'networkidle0' });
waitUntil参数
networkidle0:等待所有网络请求完成(0 个网络连接持续至少 500ms)。
networkidle2:等待网络请求低于 2 个时(在网络连接减少到 2 个或更少时持续至少 500ms)。
load:等待 DOMContentLoaded 事件触发。
domcontentloaded:同 load。
networkidle:同 networkidle0。
其中
networkidle0表示:when there are no more than 0 network connections for at least 500 ms.
newwordidle2表示:when there are no more than 0 network connections for at least 500 ms.
setDefaultTimeouts
https://pptr.dev/api/puppeteer.page.setdefaulttimeout/
Same like above, this will let one update all timeouts at once or just the one they want. Will remove the need for setDefaultNavigationTimeout or setDefaultWaitTimeout if happens and window for more useful api
PS: I have a project where I have at least thousands of waitFor cases for some reason and hundreds of navigation calls, this feels really promising in that sense where people have lots of test cases.
设置 Puppeteer 的默认超时时间(适用于所有超时相关的方法,如 page.waitForSelector、page.waitForFunction 等)
waitFor
waitFor 用于等待某个条件满足,可以是时间、选择器或某个函数的结果。
Puppeteer 提供了多种等待方式,例如:
page.waitForSelector(selector):等待特定选择器出现。
page.waitForTimeout(ms):等待指定的毫秒数。
page.waitForFunction(fn):等待指定的函数返回 true。
等待一个元素或表达式满足特定条件。
await page.waitForSelector('#my-element');
await page.waitForFunction('document.querySelector("#my-element").textContent === "Hello"');
灵活等待,自定义条件,局部等待
setDefaultNavigationTimeout
https://pptr.dev/api/puppeteer.page.setdefaultnavigationtimeout/
设置页面导航相关操作的超时时间(如 page.goto()、page.waitForNavigation())。
sefaultTimeout 与 setDefaultNavigationTimeout 的区别
setDefaultTimeout: 设置的是全局超时时间,影响所有等待方法。
setDefaultNavigationTimeout: 设置的是仅影响导航操作的超时时间。
总结
方法/属性 | 适用范围 | 默认值 |
---|---|---|
waitUntil | 导航完成条件 | load |
waitFor | 等待某个条件(选择器、时间、函数等) | 无默认值 |
setDefaultTimeout | 全局超时时间,影响所有等待方法 | 30 秒 |
setDefaultNavigationTimeout | 导航操作的超时时间(覆盖全局超时) | 30 秒 |
转载本站文章《Puppeteer页面请求waitUntil、waitfor、setDefaultTimeout》,
请注明出处:https://www.zhoulujun.cn/html/webfront/browser/Puppeteer/9436.html