如何检查Puppeteer和纯JavaScript可见的元素? [英] How can I check that an element is visible with Puppeteer and pure JavaScript?

查看:623
本文介绍了如何检查Puppeteer和纯JavaScript可见的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过木偶和纯JavaScript(不是jQuery)检查DOM元素是否可见, 我怎样才能做到这一点? 可见是指该元素通过CSS显示,而不是隐藏(例如,通过 display:none )。

I wish to check that a DOM element is visible with Puppeteer and pure JavaScript (not jQuery), how can I do this? By visible I mean that the element is displayed through CSS, and not hidden (f.ex. by display: none).

例如,我可以确定是否通过CSS规则 display:none 隐藏我的元素 #menu ,方法如下:

For example, I can determine whether my element #menu is not hidden via CSS rule display: none, in the following way:

const isNotHidden = await page.$eval('#menu', (elem) => {
  return elem.style.display !== 'none'
})

我一般如何确定元素是否被隐藏,而不仅仅是通过 display:none

How can I determine in general though if the element is hidden or not, and not just through display: none?

推荐答案

我发现Puppeteer为此目的提供了一种API方法: Page.waitForSelector ,通过其可见选项。我不知道后一个选项,但是它让您等到某个元素可见。

I found that Puppeteer has an API method for this purpose: Page.waitForSelector, via its visible option. I wasn't aware of the latter option, but it lets you wait until an element is visible.

await page.waitForSelector('#element', {
  visible: true,
})

您可以通过 hidden 选项等待元素被隐藏。

Conversely you can wait for an element to be hidden, via the hidden option.

我认为这是惯用的答案,关于Puppeteer API。感谢Colin Cline,尽管我认为他的回答可能对通用JavaScript解决方案很有用。

I think this is the idiomatic answer, with regards to the Puppeteer API. Thanks to Colin Cline though as I think his answer is probably useful as a general JavaScript solution.

这篇关于如何检查Puppeteer和纯JavaScript可见的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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