木偶操纵者等待第一个元素加载

puppeteer waits for first element to load

我正在尝试检查第一个元素 class 以加载到我的页面中以执行我的代码。例如,我的页面可以有 3 种不同的状态,它可以有一个带有 class .a 的弹出窗口,或者它可以有一个带有 class .b 的页面或一个带有 class .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)
})

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

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

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

    await page.goto(' { 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/then,就像这样:

    await page.goto(' { 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);

{ 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(),
        ]);