【问题标题】:Selenium C# Webdriver How to detect if element is visibleSelenium C# Webdriver如何检测元素是否可见
【发布时间】:2012-06-11 15:42:43
【问题描述】:

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

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

据我了解,RenderedWebElement 类以及其他变体已被弃用。所以没有强制转换。

谢谢。

【问题讨论】:

  • 应该有一个 WebElement.isDisplayed() 来检查元素是否可见
  • 不幸的是捕获异常是要走的路。 Displayed 和 Enabled 并不总是呈现可操作元素,这意味着该项目可以同时显示和启用,但仍然不能点击。当元素不在视图中时会发生这种情况(在某些浏览器中),您通常需要做的是滚动到元素以使其可见。

标签: selenium webdriver visibility visible


【解决方案1】:

对于 Java,RemoteWebElement 上有 isDisplayed() - isEnabled() 也是如此

在 C# 中,有一个 Displayed & Enabled 属性。

两个元素都必须为真,元素才能出现在页面上并且对用户可见。

在“html无论如何都还在,所以可以找到”的情况下,只需检查 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;
}

【讨论】:

  • 我一定不同意,因为element.Enabled 只会为显式禁用的输入元素返回false,因此可见性可以简单地由element.Displayed 属性确定。
【解决方案2】:

目前对这个问题的回答似乎已经过时了:在 WebDriver 3.13 中,只要元素存在于页面上,DisplayedEnabled 属性都将返回 true,即使它位于视口之外。以下 C# 代码适用于 WebDriver 3.13(来自 this StackOverflow answer):

{
    return (bool)((IJavaScriptExecutor)Driver).ExecuteScript(@"
        var element = arguments[0];
        var boundingBox = element.getBoundingClientRect();
        var cx = boundingBox.left + boundingBox.width/2, cy = boundingBox.top + boundingBox.height/2;
        return !!document.elementFromPoint(cx, cy);
        ", element);
}

【讨论】:

  • 你知道这个的c#版本吗?
  • 是的。上面的例子是 C#。
【解决方案3】:

有一个简单的方法可以做到这一点,如下所示:

public bool ElementDisplayed(By locator)
{
     new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(condition: ExpectedConditions.PresenceOfAllElementsLocatedBy(locator));
     return driver.FindElement(locator).Displayed ;
}

【讨论】:

    【解决方案4】:

    您可以使用以下内容:

    WebDriver web = new FirefoxDriver(;
    String visibility = web.findElement(By.xpath("//your xpath")).getCssValue("display");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2011-02-08
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多