最新版本的 Selenium DotNet Webdriver (2.22.0) 有没有办法在单击/交互之前检查元素是否可见?
我发现的唯一方法是尝试处理在您尝试发送密钥或单击它时发生的 ElementNotVisible 异常。不幸的是,这只发生在尝试与元素交互之后。我正在使用递归函数来查找具有特定值的元素,其中一些元素仅在某些场景中可见(但无论如何它们的html仍然存在,因此可以找到它们)。
据我了解,RenderedWebElement 类以及其他变体已被弃用。所以没有铸造。
谢谢。
最新版本的 Selenium DotNet Webdriver (2.22.0) 有没有办法在单击/交互之前检查元素是否可见?
我发现的唯一方法是尝试处理在您尝试发送密钥或单击它时发生的 ElementNotVisible 异常。不幸的是,这只发生在尝试与元素交互之后。我正在使用递归函数来查找具有特定值的元素,其中一些元素仅在某些场景中可见(但无论如何它们的html仍然存在,因此可以找到它们)。
据我了解,RenderedWebElement 类以及其他变体已被弃用。所以没有铸造。
谢谢。
对于 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;
}
有一种简单的方法可以做到这一点,如下所示:
public bool ElementDisplayed(By locator)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(condition: ExpectedConditions.PresenceOfAllElementsLocatedBy(locator));
return driver.FindElement(locator).Displayed ;
}
这个问题的当前答案似乎已经过时了:使用 WebDriver 3.13 ,只要元素存在于页面上,即使它在视口之外,Displayed和属性都将返回 true。Enabled以下 C# 代码适用于 WebDriver 3.13(来自此 StackOverflow 答案):
{
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);
}
您可以使用以下内容:
WebDriver web = new FirefoxDriver(;
String visibility = web.findElement(By.xpath("//your xpath")).getCssValue("display");