无法从 OpenQA.Selenium.IWebElement 转换为 Open.Qa.Selenium.By

Ric*_*d C 1 c# selenium

我一直致力于使我的 Selenium 框架成为页面工厂,但是我正在努力让 Wait.Until 命令在我的扩展类中工作。

public static void Wait(this IWebElement element, IWebDriver driver, float TimeOut)
{
    WebDriverWait Wait = new WebDriverWait(driver, TimeSpan.FromSeconds(TimeOut));
    return Wait.Until(ExpectedConditions.ElementIsVisible(element));
}
Run Code Online (Sandbox Code Playgroud)

如果我使用上面的代码,我会收到错误无法从 OpenQA.Selenium.IWebElement 转换为 Open.Qa.Selenium.By

任何建议我如何修改上面的代码以使其在我使用的 By 模型中工作?

mrf*_*ter 6

没有ExpectedConditions.ElementIsVisible(IWebElement)。不幸的是,你只能使用ElementIsVisibleBy对象。

如果合适,您可以替换为ExpectedConditions.ElementToBeClickable(IWebElement),这是一种稍微不同的情况,除了可见之外,它还检查元素是否已启用。但这可能满足您的要求。

或者,您可以只调用element.Displayedcustom WebDriverWait,确保忽略或捕获NoElementException

这是我为您的情况使用和更改的旧实现,现在可能有更简洁的方法:

new WebDriverWait(driver, TimeSpan.FromSeconds(TimeOut))
{
    Message = "Element was not displayed within timeout of " + TimeOut + " seconds"
}.Until(d => 
{
    try
    {
        return element.Displayed;
    }
    catch(NoSuchElementException)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面代码的快速解释......它会尝试element.Displayed一遍又一遍地执行,直到它返回true。当element不存在时,它将抛出一个NoSuchElementException将返回的 ,false因此WebDriverWait将继续执行,直到两者都element存在,并element.Displayed返回真,或TimeOut达到。