Puppeteer 流程​​逻辑,检查导航是否发生(与等待)

寻找一些反馈。在 Puppeteer 中,我想检查导航是否已经发生,如果有则做一些事情,如果没有发生则做其他事情(例如再试一次)。我想出的两种方法是:


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

        }

    }

}

但是我的理解是,尝试/捕获流逻辑并不理想。我的选择是这样的:


let t = 0;

busy: while(await page.url() != finalURL) {

    await page.click('#tryAgainLink');

    await page.waitForTimeout(1500);

    t++;

    if(t > 400) {

        break busy;

    }

}

我想知道我是否应该waitForNavigatin在那里,但如果没有,我将不得不再次捕获抛出的错误。我的意思是测试这个,但我不确定await page.url()while 循环是否会在导航发生时触发几次,和/或是否会破坏页面上下文。


有没有比上面两种方法更好的方法呢?第一个确实有效,我很想保持原样。谢谢。


尚方宝剑之说
浏览 112回答 3
3回答

BIG阳

您应该能够执行以下操作:await page.waitForFunction((finalUrl) => {  return document.location === finalUrl}, {}, finalUrl).catch(retry)但它可能更简单:await page.waitForResponse(finalUrl).catch(retry)

饮歌长啸

也许是这样的:if (page.url() !== finalURL) { // await is not needed here&nbsp; &nbsp; let t = 0;&nbsp; &nbsp; busy: while(t < 400) { // was '> 400' a typo?&nbsp; &nbsp; &nbsp; &nbsp; const [_, navigation] = await Promise.allSettled([&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; page.click('#tryAgainLink'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; page.waitForNavigation(),&nbsp; &nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; &nbsp; if (navigation.status === 'fulfilled') break busy;&nbsp; &nbsp; &nbsp; &nbsp; t++;&nbsp; &nbsp; &nbsp; &nbsp; await page.waitForTimeout(1500);&nbsp; &nbsp; }}

莫回无

我使用这种方法:async function isNavigation() {&nbsp; try {&nbsp; &nbsp; await page.evaluate(() => console.log('any code'))&nbsp; &nbsp; return false&nbsp; } catch (ex) {&nbsp; &nbsp; // check error, should be:&nbsp; &nbsp; // "Execution context was destroyed, most likely because of a navigation"&nbsp; &nbsp; return true&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript