本文介绍了单击 puppeteer 中的元素后,如何等待网络空闲?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击 puppeteer 中的元素后如何等待网络空闲?

How can I wait for network idle after click on an element in 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');

UPD:点击元素后没有导航

UPD: No navigation after the element was clicked

推荐答案

我遇到了类似的问题,并在 Puppeteer Control 网络空闲等待时间问题上找到了解决方法来满足我的需求:https://github.com/GoogleChrome/puppeteer/issues/1353#issuecomment-356561654

I ran into a similar issue and found the workaround function on the Puppeteer Control networkidle wait time issue to suit my needs:https://github.com/GoogleChrome/puppeteer/issues/1353#issuecomment-356561654

基本上,您可以创建一个自定义函数,并在任何其他步骤之前调用它:

Essentially, you can create a custom function, and call that prior to any additional steps:

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'
]);

这篇关于单击 puppeteer 中的元素后,如何等待网络空闲?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:12