puppeteer wait for network idle after click

白昼怎懂夜的黑 提交于 2020-01-24 19:31:09

问题


None of the existing Q&As have a clean solution for this question, e.g.,

  • puppeteer wait for page update after button click (no navigation)
  • How can I wait for network idle after click on an element in puppeteer?

So here is a simple working example for people to see/try/fix:

const puppeteer = require('puppeteer');

(async() => {
  const browser = await puppeteer.launch({headless: true});
  try {
    const page = await browser.newPage();

    await page.setViewport({width: 800,height: 800});
    const response = await page.goto(`https://stock.finance.sina.com.cn/usstock/quotes/TSLA.html`, {
        waitUntil: 'networkidle0'
      });
    //console.log(await page.content());

    let selector = `div.kke_menus_tab_edage > div:nth-child(6) > a`
    await page.waitForSelector(selector)
    await page.click(selector)

    const inputElement = await page.$('div.sec.clearfix div.block.block_hq')
    await inputElement.screenshot({path: 'sina-finance.png'})

  } catch (err) {console.log(err.message);}
  finally {
    await browser.close();
  }
})()

So, in summary,

  • The click does not trigger any navigation
  • The inputElement already exist, even before clicking so can't wait on that.

Any simple solution like page.waitForNavigation, e.g., page.waitForNetwork({waitUntil: 'networkidle0'})?
Else, I'll raise a bug to the puppeteer project to provide one. Thx.


回答1:


If you know the specific request being made when you click the button, you can easily use the page.waitForResponse() method.

e.g.

const pageClick = page.click(selector);
const response = page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200);

await Promise.all([
    pageClick,
    response
]);


来源:https://stackoverflow.com/questions/59831875/puppeteer-wait-for-network-idle-after-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!