http://www.51testing.com/html/91/79191-829759.html
- 关于存在不可见属性的元素,对元素操作时,出现报如下异常的情况及处理办法:
Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with Command duration or timeout: 31 milliseconds
首先,得排除是否是定位的xpath路径有问题,如果是用xpath定位,其中用@class属性来定位,也会报这个错误(特别是class中含有复合类的定位)。下面用备份软件删除任务的弹出div区中的确认按钮定位为例:
WebElement cf_button=driver.findElement(By.xpath("//div[@class='ui-dialog-buttonset']"));
用上面的class定位,也是有问题的。用下面的路径也是有问题的,都会报上面提到的异常内容。
Xpath=//div[@class=ui-dialog-buttonpane ui-widget-content ui-helper-clearfix]/div/button
这个xpath中的class属于复合类。
如果用下面的定位,就不会报这个异常:
WebElement cf_button=driver.findElement(By.xpath("//div[4]/div[3]/div[1]/button"));
上面的元素定位,可通过元素对象的方法isDisplayed()检测元素是否可显示的,如果得到不可显示,操作该元素时会报上面提到的异常,检测语句如下:
if(!(cf_button.isDisplayed())){System.out.println("Element is not displayed!"); };
第2种情况:就是元素的样式或父级及以上元素含有不可显示属性,以致在有些浏览器中(FirefoxDriver)不能操作,但在正常的浏览器中它是可见和可用的。那么需要检查元素是否具备如下特性:
- visibility!= hidden
- display != none (is also checked against every parent element)
- opacity != 0 (in rc2 this is no longer checked for clicking an element)
- height and width are both > 0
- for an input, the attribute type != hidden
如果有不符上面的特性之一,那么就用js脚本来处理
如下面代码:
WebElement label = driver.findElement(By.xpath("// label[text()='User Name:' and not(contains(@style,'display: none'))]"));