mat*_*ish 12 javascript node.js puppeteer
单击 puppeteer 中的元素后,如何等待网络空闲?
const browser = await puppeteer.launch({headless: false});
await page.goto(url, {waitUntil: 'networkidle'});
await page.click('.to_cart'); //Click on element trigger ajax request
//Now I need wait network idle(Wait for the request complete)
await page.click('.to_cart');
Run Code Online (Sandbox Code Playgroud)
UPD:点击元素后没有导航
我遇到了类似的问题,并找到了 Puppeteer Control 网络空闲等待时间问题的解决方法来满足我的需求: https ://github.com/GoogleChrome/puppeteer/issues/1353#issuecomment-356561654
本质上,您可以创建一个自定义函数,并在执行任何其他步骤之前调用该函数:
function waitForNetworkIdle(page, timeout, maxInflightRequests = 0) {
page.on('request', onRequestStarted);
page.on('requestfinished', onRequestFinished);
page.on('requestfailed', onRequestFinished);
let inflight = 0;
let fulfill;
let promise = new Promise(x => fulfill = x);
let timeoutId = setTimeout(onTimeoutDone, timeout);
return promise;
function onTimeoutDone() {
page.removeListener('request', onRequestStarted);
page.removeListener('requestfinished', onRequestFinished);
page.removeListener('requestfailed', onRequestFinished);
fulfill();
}
function onRequestStarted() {
++inflight;
if (inflight > maxInflightRequests)
clearTimeout(timeoutId);
}
function onRequestFinished() {
if (inflight === 0)
return;
--inflight;
if (inflight === maxInflightRequests)
timeoutId = setTimeout(onTimeoutDone, timeout);
}
}
// Example
await Promise.all([
page.goto('https://google.com'),
waitForNetworkIdle(page, 500, 0), // equivalent to 'networkidle0'
]);
Run Code Online (Sandbox Code Playgroud)