puppeteer 在按钮点击后等待页面更新(无导航) [英] puppeteer wait for page update after button click (no navigation)

查看:178
本文介绍了puppeteer 在按钮点击后等待页面更新(无导航)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次尝试 puppeteer,真是太棒了.单击按钮后,我需要等待页面获取并呈现新数据.这不会导致导航(网址相同),因此以下代码不起作用(它给出超时异常):

Trying puppeteer for the first time and it is amazing. I need to wait for a page to fetch and render new data after a button click. This does not cause a navigation (the url is the same) so the following code does not work (it gives timeout exception):

await Promise.all([
    myButton.click()
    page.waitForNavigation()
])

等待页面在点击时获取/呈现异步数据的正确方法是什么?

What's the correct way to wait for the page to fetch/render async data on click?

推荐答案

假设 DOM 以某种方式发生变化,您可以等待特定的元素或选择器.

Assuming the DOM changes in some way, you can wait for a specific element or selector.

可能会出现图像.

await myButton.click();
await page.waitForSelector('img.success');

也许某个具有 ID 属性的元素被插入到 DOM 中.

Maybe some element with an ID attribute is inserted into the DOM.

await myButton.click();
await page.waitForSelector('#newElementThatAppeared');

如果您不熟悉 DOM 选择器,您可以阅读 这里这里.它们功能强大且易于使用.

If you're unfamiliar with DOM selectors, you can read up here and here. They're powerful and easy to use.

更新 - 自定义等待谓词.

Update - Custom wait predicate.

如果我们总是知道长度...

If we always know the length...

await myButton.click();
await page.waitFor(() => document.querySelectorAll('ul.specialList li').length > 5);

如果我们知道长度会增加

If we know the length will increase

const listSize = await page.evaluate(() => document.querySelectorAll('ul.specialList li').length);
await myButton.click();
await page.waitFor(() => document.querySelectorAll('ul.specialList li').length > listSize);

这篇关于puppeteer 在按钮点击后等待页面更新(无导航)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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