人偶等待第一个元素加载

时间:2018-12-05 03:45:17

标签: puppeteer

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

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执行其中之一后仍在运行。我该如何解决?

2 个答案:

答案 0 :(得分:0)

我在doc中找不到Promise.race()接受{timeout: ...}参数的地方。

如果您要设置超时,我会在Puppeteer的page.waitForSelector中进行。

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

而且,但这将是我个人编写的方式,我将等待所有内容,而不是等待/然后混合,就像这样:

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

答案 1 :(得分:0)

{ visible: true}是要考虑的东西。就像:

const elementHandle = await Promise.race([
            this.page.waitForSelector(selector_1, { timeout: 4000, visible: true })
            .catch(),
            this.page.waitForSelector(selector_2, { timeout: 4000, visible: true })
            .catch(),
        ]);