点击后等待网络空闲

点击后等待网络空闲

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

问题描述

现有的 Q&As 都没有针对此问题的清晰解决方案,例如,

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

所以这是一个简单的工作示例,供人们查看/尝试/修复:

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();
  }
})()

总之,

  • 点击不会触发任何导航
  • inputElement 已经存在,甚至在点击之前就已经存在,所以不能等待.
  • The click does not trigger any navigation
  • The inputElement already exist, even before clicking so can't wait on that.

任何简单的解决方案,例如 page.waitForNavigation,例如 page.waitForNetwork({waitUntil: 'networkidle0'})?
否则,我将向 puppeteer 项目提出一个错误以提供一个错误.谢谢.

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.

推荐答案

如果您知道单击按钮时发出的特定请求,则可以轻松使用 page.waitForResponse() 方法.

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

例如

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

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

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

08-23 01:13