How to wait for event triggered page reloads with Puppeteer?

杀马特。学长 韩版系。学妹 提交于 2019-12-24 18:57:37

问题


I'm trying safely handle the behavior of a page which uses an in-browser event on a select element to trigger a page reload (POST). The URL is the same but the page reloads with the same HTML and the only difference is the sort order of content in a table. I tried several methods but somehow none are reliable, how can I achieve something like this:

    try {
        await page.select('select[name=sort]', 'size'); 
        await page.waitForNextPageReload();
        await page.waitForSelector('select[name=sort]');
    } catch (error) {
        console.log('Error sorting page.');
    }

Basically, waitForNextPageReload doesn't exist but I'm looking for something which would provide similar results. I tried to add 'delays' but I'm looking for something more reliable to manage errors correctly.


回答1:


There may be a race condition between selecting and navigation promises (see examples here or here). Can you try this approach?

await Promise.all([
  page.select('select[name=sort]', 'size'),
  page.waitForNavigation(),
]);

await page.waitForSelector('select[name=sort]');



回答2:


Try page.waitForNavigation.

Quoting from puppeteer docs:

This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate.

It seems good for your use case where you are indirectly reloading the page



来源:https://stackoverflow.com/questions/55084570/how-to-wait-for-event-triggered-page-reloads-with-puppeteer

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