Puppeteer flow logic, check if navigation has occurred (vs wait for)

十年热恋 提交于 2020-12-12 21:51:31

问题


Looking for some feedback. In Puppeteer, I want to check if navigation has occurred, do something if it has, else do something else if it hasn't (e.g. try again). The two ways of doing it I've come up with are:

if (await page.url() != finalURL) {
    let t = 0;  
    busy: while(t > 400) {
        try {
            await Promise.all([
                await page.click('#tryAgainLink'),
                await page.waitForNavigation(),
            ]);
            break busy;
        } catch(err) {
            // navigation didn't happen
            t++;
            await page.waitForTimeout(1500);
        }
    }
}

However my understanding is that it's not ideal to try/catch for flow logic. My alternative is something like this:

let t = 0;
busy: while(await page.url() != finalURL) {
    await page.click('#tryAgainLink');
    await page.waitForTimeout(1500);
    t++;
    if(t > 400) {
        break busy;
    }
}

I wonder if I should have a waitForNavigatin in there, but again would have to catch the thrown error if it hasn't. I mean to test this, but I am not sure if that await page.url() for the while loop will fire a couple of times while a navigation is occurring, and/or if that will break the page context.

Is there a better way than the above two methods? The first one does work, and I am tempted to leave it as is. Thank you.


回答1:


You should be able to do something like:

await page.waitForFunction((finalUrl) => {
  return document.location === finalUrl
}, {}, finalUrl).catch(retry)

but it might be simpler to just:

await page.waitForResponse(finalUrl).catch(retry)



回答2:


Maybe something like this:

if (page.url() !== finalURL) { // await is not needed here
    let t = 0;
    busy: while(t < 400) { // was '> 400' a typo?
        const [_, navigation] = await Promise.allSettled([
            page.click('#tryAgainLink'),
            page.waitForNavigation(),
        ]);

        if (navigation.status === 'fulfilled') break busy;

        t++;
        await page.waitForTimeout(1500);
    }
}


来源:https://stackoverflow.com/questions/64342023/puppeteer-flow-logic-check-if-navigation-has-occurred-vs-wait-for

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