puppeteer 等待第一个元素加载 [英] puppeteer waits for first element to load

查看:299
本文介绍了puppeteer 等待第一个元素加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查要加载到我的页面中的第一个元素类以执行我的代码.例如,我的页面可以有 3 种不同的状态,它可以具有类 .a 的弹出窗口,或者具有类 .b 的页面或类 .b 的页面代码>.c.所以我想等待其中一个加载并先加载哪个.我尝试使用 Promise.race 来做到这一点.我的代码:

I'm trying to check the first element class to load in my page to execute my code. For example, my page can have 3 different states, it can have a popup with class .a or it can have a page with class .b or a page with class .c. So I would like to wait one of them to load and get which one loaded first. I tried to do it with Promise.race. My code:

await page.goto('myurl', { waitUntil: 'networkidle2', timeout: 30000 }).then(async () => {
await Promise.race([
     page.waitForSelector('.a'),
     page.waitForSelector('.b'),
     page.waitForSelector('.c'),
   ], {timeout: 60000 })
   console.log('done loading one of the 3 elements')
}).catch(e => {
  console.log(e)
})

但在那之后,我得到一个错误,例如类 .b 无法在 60000 毫秒内加载.不是应该工作吗?Promise.race 在其中一个执行后仍在运行.我该如何解决这个问题?

But after that, I get en error that for example class .b could not load in 60000ms. Isnt it supposed to work? Promise.race is still running after one of them executed. How can I solve this?

推荐答案

我在 doc 其中 Promise.race() 需要一个 {timeout: ...}论证.

I can't find a place in the doc where Promise.race() takes a {timeout: ...} argument.

如果你想设置超时,我会在 Puppeteer 的 page.waitForSelector 中设置.

If you want to set a timeout, I would do it in the page.waitForSelector in Puppeteer.

    await page.goto('https://stackoverflow.com/questions/53624870/puppeteer-waits-for-first-element-to-load', { waitUntil: 'networkidle2', timeout: 30000 })
        .then(async () => {
            let elementHandle = await Promise.race([
                page.waitForSelector('.post-text', {timeout: 60000}),
                page.waitForSelector('.should-fail', {timeout: 60000}),
                page.waitForSelector('.should-fail-2', {timeout: 60000}),
            ]);

            console.log(elementHandle != null);
        })
        .catch(e => {
            console.log(e);
        });

而且,但这将是我个人的写作方式,我会等待一切,而不是像这样混合等待/然后:

And also, but that would be my personnal way of writing it, I would await everything and not mix await/then, like so :

    await page.goto('https://stackoverflow.com/questions/53624870/puppeteer-waits-for-first-element-to-load', { waitUntil: 'networkidle2', timeout: 30000 })
        .catch(e => console.error(e));

    let elementHandle = await Promise.race([
        page.waitForSelector('.post-text', {timeout: 60000}),
        page.waitForSelector('.should-fail', {timeout: 60000}),
        page.waitForSelector('.should-fail-2', {timeout: 60000})
    ]);

    console.log(elementHandle != null);

这篇关于puppeteer 等待第一个元素加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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