puppeteer:如何在 SPA 中等待页面? [英] puppeteer: How to wait for pages in SPA's?

查看:72
本文介绍了puppeteer:如何在 SPA 中等待页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 puppeteer 浏览 SPA,我在这里面临的问题是我无法等待页面加载然后继续我的程序.

I am trying to navigate through an SPA with puppeteer, the problem I am facing here is that I am unable to wait for the page to load then proceed with my program.

我填写了一个表单然后点击提交,根据表单的内容,可以加载不同的页面,所以我不能使用 page.waitFor(Selector) 因为可以有很多不同的页面取决于输入.

I fill a form and then click submit, depending on the contents of the form, different pages can be loaded so I can't use page.waitFor(Selector) as there can be many different pages depending on the input.

我尝试使用 waitUntil: load、networkidle2、networkidle0、domcontentloaded,但它们都在元素加载之前触发.

I tried using waitUntil: load, networkidle2, networkidle0, domcontentloaded but all of them trigger before the elements are loaded.

我尝试自动化的页面是链接.(如果你想自己检查,然后选择预订参考并随机填写详细信息,然后按继续.)

The page I am trying to automate is Link. (If you want to check for yourself, then choose booking reference and fill out random details and press continue.)

在链接中选择预订参考"后,我用 puppeteer 填写了详细信息,然后按了继续按钮,我不知道如何在不依赖选择器的情况下等待页面完全加载.

After choosing "booking-reference" in the link I fill in the details with puppeteer and then press the continue button, What I cannot figure out is how to wait for the page to be completely loaded without relying on selectors.

推荐答案

我想你应该知道那些页面是什么,并使用 Promise.racepage.waitFor每个页面,像这样:

I think you should know what those pages are and use Promise.race with page.waitFor for each page, like this:

const puppeteer = require('puppeteer');

const html = `
<html>
  <body>
    <div id="element"></div>
    <button id="button">load</button>

    <script>
      document.getElementById('button').addEventListener("click", () => {
        document.getElementById('element').innerHTML =
          '<div id="element' + (Math.floor(Math.random() * 3) + 1)  + '"></div>';
      });
    </script>
  </body>
</html>`;

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(`data:text/html,${html}`);

  await page.click('#button');

  const element = await Promise.race([
    page.waitFor('#element1'),
    page.waitFor('#element2'),
    page.waitFor('#element3')
  ]);

  console.log(await (await element.getProperty('id')).jsonValue());
  await browser.close();
})();

这篇关于puppeteer:如何在 SPA 中等待页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆