puppeteer waits for first element to load

和自甴很熟 提交于 2019-12-11 17:41:51

问题


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

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/53624870/puppeteer-waits-for-first-element-to-load

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!