Selenium C# Webdriver 如何检测元素是否可见 [英] Selenium C# Webdriver How to detect if element is visible

查看:34
本文介绍了Selenium C# Webdriver 如何检测元素是否可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最新版本的 Selenium DotNet Webdriver (2.22.0) 中有没有办法在点击/交互之前检查元素是否可见?

Is there a way in the latest version of Selenium DotNet Webdriver (2.22.0) to check to see if an element is visible before clicking/interacting with it?

我发现的唯一方法是尝试处理当您尝试发送密钥或单击它时发生的 ElementNotVisible 异常.不幸的是,这只发生在尝试与元素进行交互之后.我正在使用递归函数来查找具有特定值的元素,其中一些元素仅在某些情况下才可见(但无论如何它们的 html 仍然存在,因此可以找到它们).

The only way I've found is to try to handle the ElementNotVisible exception that occurs when you try to send keys, or click on it. Unfortunately this only occurs after an attempt to interact with the element has been made. I'm using a recursive function to find elements with a certain value, and some of these elements are only visible in certain scenarios (but their html is still there no matter what, so they can be found).

我的理解是 RenderedWebElement 类以及其他变体已被弃用.所以没有强制转换.

It's my understanding that the RenderedWebElement class is deprecated as well other variants. So no casting to that.

谢谢.

推荐答案

对于 Java,RemoteWebElement 上有 isDisplayed() - 以及 isEnabled()

For Java there is isDisplayed() on the RemoteWebElement - as well is isEnabled()

在 C# 中,有一个 Displayed &启用属性.

In C#, there is a Displayed & Enabled property.

要使元素在页面上并且对用户可见,两者都必须为真.

Both must be true for an element to be on the page and visible to a user.

在无论如何,html仍然存在,因此可以找到它们"的情况下,只需选中两个 isDisplayed (Java)/Displayed (C#) AND isEnabled (Java)/Enabled (C#).

In the case of "html is still there no matter what, so they can be found", simply check BOTH isDisplayed (Java) / Displayed (C#) AND isEnabled (Java) / Enabled (C#).

示例,在 C# 中:

public void Test()
{
    IWebDriver driver = new FirefoxDriver();
    IWebElement element = null;
    if (TryFindElement(By.CssSelector("div.logintextbox"), out element)
    {
        bool visible = IsElementVisible(element);
        if  (visible)
        {
            // do something
        }
    }
}

public bool TryFindElement(By by, out IWebElement element)
{
    try
    {
        element = driver.FindElement(by);
    }
    catch (NoSuchElementException ex)
    {
        return false;
    }
    return true;
}

public bool IsElementVisible(IWebElement element)
{
    return element.Displayed && element.Enabled;
}

这篇关于Selenium C# Webdriver 如何检测元素是否可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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