0

我编写了一个 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

4

1 回答 1

0

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

但是,当您诱导Wait.Until以及提供一组可以使用WebDriverWait 类等待的常见条件的ExpectedConditions 类时,WebDriver实例根据ExpectedConditions子句等待,在您的情况下是ExpectedConditions.ElementToBeClickable 方法(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 找到的,这是与您在从下面的列表中选择定位器时使用的定位器策略相关的事实:

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

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

于 2018-02-24T13:57:44.173 回答