Puppeteer 流程​​逻辑,检查导航是否发生(vs 等待) [英] Puppeteer flow logic, check if navigation has occurred (vs wait for)

查看:43
本文介绍了Puppeteer 流程​​逻辑,检查导航是否发生(vs 等待)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

您应该能够执行以下操作:

You should be able to do something like:

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

但可能更简单:

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

这篇关于Puppeteer 流程​​逻辑,检查导航是否发生(vs 等待)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆