如何使监视功能等待 puppeteer 中的 html 元素 [英] How can I make a monitoring function to wait for an html element in puppeteer

查看:54
本文介绍了如何使监视功能等待 puppeteer 中的 html 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何制作一个函数,等待某个 CSS 选择器加载到 puppeteer 中?

How can I make a function that waits until a certain CSS selector loads in puppeteer?

我想一遍又一遍地刷新页面,直到出现.product-form__add-to-cart",然后我希望它继续使用代码.

I want to refresh the page over and over until the '.product-form__add-to-cart' is present, then I want it to continue on with the code.

推荐答案

对应的puppeteer方法为page.waitForSelector.

The corresponding puppeteer method is page.waitForSelector.

示例:

await page.waitForSelector('.product-form__add-to-cart')

但是,如果您需要重新加载页面以获取所需元素(可能是因为您访问的站点在访问之间可能看起来不同),那么您只需检查页面呈现后该元素是否存在于 DOM 中,以及不是:那你可以试试page.重新加载.

But if you need to reload the page to get the desired element (maybe because the site you are visiting can look different between visits) than you can just check if the element is present in the DOM after the page is rendered and if not: then you can try to page.reload it.

await page.goto(url, { waitUntil: 'domcontentloaded' })
const selectorExists = await page.$('.product-form__add-to-cart')

if (selectorExists !== null) {
  // do something with the element
} else {
  await page.reload({ waitUntil: 'domcontentloaded' })
}

您也可以在循环中执行此操作,您可以在其中 break 如果选择器出现,但要小心:如果它从不出现,你将陷入无限循环!设置最大尝试次数.

You can do it in a loop as well, where you break if the selector appears, but be careful: if it never shows up you will end up in an endless loop! Set a maximum number of tries.

如果您确定在循环中运行它直到选择器出现:那么您可以尝试使用 while 循环:

If you are sure about running it in a loop until the selector appears: then you can try with a while loop:

await page.goto(url, { waitUntil: 'domcontentloaded' })
let selectorExists = await page.$('.product-form__add-to-cart')

while (selectorExists === null) {
  await page.reload({ waitUntil: 'domcontentloaded' })
  selectorExists = await page.$('.product-form__add-to-cart')
}
// if condition meets the script will go on

正如我之前所说:你可能会以这样的无限循环结束,所以要小心.

As I said earlier: you can end up with an endless loop like this, so be careful.

这篇关于如何使监视功能等待 puppeteer 中的 html 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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