【问题标题】:How can I wait for network idle after click on an element in puppeteer?单击 puppeteer 中的元素后如何等待网络空闲?
【发布时间】:2019-06-20 00:27:03
【问题描述】:

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:点击元素后没有导航

【问题讨论】:

标签: javascript node.js puppeteer


【解决方案1】:

我遇到了类似的问题,并在 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'
]);

【讨论】:

    【解决方案2】:

    Puppeteer 文档中有两种方法。

    例子:

    await Promise.all([
        page.waitForRequest(callback), 
        page.waitForResponse(callback)
    ])
    

    【讨论】:

      【解决方案3】:

      直接来自the docs

      这会在页面导航到新 URL 或重新加载时解决。当您运行将间接导致页面导航的代码时,它很有用。考虑这个例子:

      const [response] = await Promise.all([
        page.waitForNavigation(), // The promise resolves after navigation has finished
        page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
      ]);
      

      【讨论】:

      • 点击元素不会导致导航
      • 请向我们提供一个 GitHub repo 以及不工作的例子,我们可以更有效地帮助你?
      • 这是一个工作示例,问题是我不知道如果单击一个元素会导致 xhr 请求并且不会导致导航(其预期行为),我该如何等待网络空闲
      • 谢谢)我试试看
      • 让我知道,以便我可以用正确的回复更新我的回复
      猜你喜欢
      • 1970-01-01
      • 2023-02-03
      • 2019-12-08
      • 2019-07-07
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      相关资源
      最近更新 更多