问题描述
我不明白.. 我已经搜索了 2 天的答案,但找不到解决此问题的单一解决方案。
代码如下(在 try catch 块中):
Presence = new webdriverwait(Driver,custTimeout);
Presence.until(ExpectedConditions.presenceOfElementLocated(By.xpath(ElementXpath)));
单独的 try catch 块:
Visisble = new webdriverwait(Driver,custTimeout);
Visisble.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(ElementXpath)));
这也显示为 FALSE:
foundElement.isdisplayed();
这失败了:
Clickable = new webdriverwait(Driver,custTimeout);
Clickable.until(ExpectedConditions.elementToBeClickable(By.xpath(ElementXpath)));
现在,当元素在屏幕上可见并且可以点击时,PRESENCE 通过和 VISIBILITY 如何/为什么失败:
ElementToClick.get(0).click();
所以基本上,元素是可见的,元素是可交互的,但是“检查是否可见”失败并出现异常。
看到“可见性”的检查基本上是寻找元素的高度和宽度,我决定手动检查一下:
ElementToClick.getAttribute("height");
ElementToClick.getAttribute("width");
两个值都是 0(但我可以在屏幕上看到元素)。
编辑:
如果这些标准方法不起作用,我该如何确定元素是否可见?
当前元素属性:
已经检查过这些帖子:
Expected condition failed: waiting for visibility of element located by By.xpath
isDisplayed() vs isVisible() in Selenium
解决方法
presenceOfElementLocated()
presenceOfElementLocated()
是检查元素是否存在于页面的 DOM 上的期望值。这并不一定意味着该元素是可见的。
public static ExpectedCondition<WebElement> presenceOfElementLocated(By locator)
Parameters:
locator - used to find the element
Returns:
the WebElement once it is located
visibilityOfElementLocated()
visibilityOfElementLocated()
是检查元素是否存在于页面的 DOM 上并且可见的期望。可见性是指元素不仅显示出来,而且高度和宽度都大于0。
public static ExpectedCondition<WebElement> visibilityOfElementLocated(By locator)
Parameters:
locator - used to find the element
Returns:
the WebElement once it is located and visible
元素显示度
isDisplayed()
的这种实现符合 WebDriver Level 2 W3C Working Draft 中提到的规范:
推荐的方法将给出一个简化的近似值 元素的可见性,但请注意,它仅依赖于 树遍历,并且只覆盖可见性检查的一个子集。
元素的可见性取决于感知可见的内容 到人眼。在这种情况下,元素的显示性不 与 visibility 或 display 样式 属性。
建议实现者确定元素的方法 可见性最初是由 Selenium 项目开发的,并且是 基于对元素性质的粗略近似和 树中的关系。一般要考虑一个元素 如果它的任何部分在边界内的画布上绘制,则可见 视口。
元素显示算法是一个布尔状态,其中true
表示元素被显示,false 表示元素
元素不显示。要计算元素上的状态,请调用
Call(bot.dom.isShown,null,element)
。如果这样做不会产生错误,则返回此函数调用的返回值。
否则返回错误代码为未知错误的错误。
此函数通常暴露给具有以下 URI 模板的 GET 请求:
/session/{session id}/element/{element id}/displayed.
结论
可以通过以下方式使人眼感知可见的元素不可见:
- 将 CSS
visibility
属性设置为hidden
- 将
display
属性设置为none
对于元素本身或者对于它的祖先。