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

C# 无法从OpenQA.Selenium.IWebElement转换为Open.Qa.Selenium.By,c#,selenium,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(Expect

我一直在努力使我的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));
}
如果我使用上面的代码,我会得到错误 无法从OpenQA.Selenium.IWebElement转换为Open.Qa.Selenium.By

有什么建议吗?我如何修改上面的代码,使其在我使用的By模型中工作

。不幸的是,您只能将ElementIsVisible与By对象一起使用

如果合适的话,您可以这样做,这是一种稍微不同的情况,它除了检查元素是否可见外,还检查元素是否已启用。但这可能满足你的要求

或者,您可以只调用自定义WebDriverWait中显示的element.Displayed,确保忽略或捕获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;
    }
}
以上代码的快速解释。。。它将尝试执行元素。反复显示,直到返回true。当该元素不存在时,它将抛出一个NOSCHELEMENTEXCEPTION,该异常将返回false,因此WebDriverWait将继续执行,直到该元素存在,并且元素。Displayed返回true,或者达到超时。

。不幸的是,您只能将ElementIsVisible与By对象一起使用

如果合适的话,您可以这样做,这是一种稍微不同的情况,它除了检查元素是否可见外,还检查元素是否已启用。但这可能满足你的要求

或者,您可以只调用自定义WebDriverWait中显示的element.Displayed,确保忽略或捕获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;
    }
}
以上代码的快速解释。。。它将尝试执行元素。反复显示,直到返回true。当该元素不存在时,它将抛出一个NOSCHELEMENTEXCEPTION,该异常将返回false,因此WebDriverWait将继续执行,直到该元素存在,并且元素。Displayed返回true,或者达到超时。

Replace

return Wait.Until(ExpectedConditions.ElementIsVisible(element));
使用下面的代码行和检查,因为这对我很有用

wait.Until(ExpectedConditions.ElementIsVisible(By.Id("ctlLogin_UserName")));
其中,ctlogin\u UserName是web元素的ID。

Replace

return Wait.Until(ExpectedConditions.ElementIsVisible(element));
使用下面的代码行和检查,因为这对我很有用

wait.Until(ExpectedConditions.ElementIsVisible(By.Id("ctlLogin_UserName")));
其中,ctlogin\u UserName是web元素的ID