【问题标题】:In Selenium Element.Displayed() is waiting too long before catching Exception在 Selenium 中,Element.Displayed() 在捕获异常之前等待太久
【发布时间】:2018-02-23 16:55:56
【问题描述】:

我写了一个 IsElementPresent 方法,它返回 true/false 是否显示元素。

这是我的方法

    public static bool IsElementPresent(this IWebElement element)
    {
        try
        {
            return element.Displayed;                                  
        }
        catch (Exception)
        {
            return false;
        }

    }

现在有时当它应该返回 false 时,element.Displayed 在捕获异常并返回 false 之前等待大约 20 秒(通过调试找到)。如果它找到元素,它工作正常。

我还将代码更改为:

public static bool IsElementPresent(this IWebElement element)
{          
    try
    {
        WebDriverWait wait = new WebDriverWait(DriverContext.Driver, TimeSpan.FromSeconds(0.1));
        wait.Until(ExpectedConditions.ElementToBeClickable(element));                
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

现在 Wait.Until 行中也发生了同样的等待。代码工作正常,但在找不到元素时只是不必要的延迟。如何找到元素是否重要。当按类找到元素时,就会发生这种特殊的延迟。大多数其他元素是使用 xpath、css 或 id 找到的。如果我错过任何信息,请告诉我。使用 VS 社区 15.5.6

【问题讨论】:

  • 您的具体问题是什么?您能总结一下您尝试自动化手动步骤吗?
  • 你能在这个元素周围发布一点 HTML 吗?
  • 我正在尝试自动化应用程序。这个问题发生在我们的一种形式上。在此页面上,我通过单击按钮执行一些操作。如果不允许此操作,Web 应用程序将在页面上抛出一些带有一些文本的错误。现在我编写了一个方法(此方法调用上述方法),它将检查是否存在错误文本(仅在没有错误时进行检查)。现在,当它到达 element.Displayed 时,它也在等待抛出异常。希望我回答了所有问题。
  • 这里是 HTML 元素。 以下表格有问题,
    “区”
    请更正excel文件中的错误。

标签: c# visual-studio selenium qwebelement


【解决方案1】:

根据 API 文档 IWebElement.Displayed 属性 gets a value indicating whether or not this element is displayed 。它不涉及等待。因此,如果任何 Exception 立即引发。

但是当你诱导 Wait.UntilExpectedConditions Class 一起提供一组可以等待使用 WebDriverWait Class 的常见条件时,WebDriver 实例等待为根据ExpectedConditions 子句,在您的情况下为ExpectedConditions.ElementToBeClickable Method (By)

ExpectedConditions.ElementToBeClickable Method (By) 被定义为期望检查元素是否可见并启用,以便您可以单击它。

  • 语法是:

    public static Func<IWebDriver, IWebElement> ElementToBeClickable(
        By locator
    )
    
  • 参数:

    locator
    Type: OpenQA.Selenium.By
    The locator used to find the element.
    
  • 返回值:

    Type: Func<IWebDriver, IWebElement>
    The IWebElement once it is located and clickable (visible and enabled).
    

因此,在使用 WebDriverWaitExpectedConditions 时,在功能上不会出现任何延迟。

最后,正如您所提到的,当类找到元素时,就会发生这种特殊的延迟。大多数其他元素是使用 xpath、css 或 id 找到的,这是与您在从下面的列表中选择 locator 时使用的 Locator Strategy 相关的事实:

  • css selector
  • link text
  • partial link text
  • tag name
  • xpath

关于定位器的性能方面已经有相当多的实验和基准测试。你可以在这里找到一些讨论:

【讨论】:

    猜你喜欢
    • 2015-07-17
    • 2018-07-24
    • 2014-12-01
    • 2021-02-05
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多