如何在 Web Driver Java 中处理 NoSuchElementException。如果元素不可见,我不想结束测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22081270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle NoSuchElementException in Web Driver Java. I dont want to end test if element is not visible
提问by user3326175
I'm trying to identify an element. If the element is there, i will click and do some operation. If the element is not there, I just it need to record a message.
我正在尝试识别一个元素。如果元素在那里,我会点击并做一些操作。如果元素不存在,我只需要记录一条消息。
I have used try
/catch
, but the test fails when the element is not there. Could someone help me here. The below code throws an exception after waiting for the default timeout.
我使用了try
/ catch
,但是当元素不存在时测试失败。有人可以在这里帮助我。以下代码在等待默认超时后抛出异常。
Note: Same question has been posted already. but only solution is to use findElements
. I dont want to go with findElements
as it takes a lot of time.
注意:同样的问题已经发布。但唯一的解决方案是使用findElements
. 我不想去,findElements
因为它需要很多时间。
try{
elemToFind = driver.findelement(By.xpath(".//div[@id='rightitems']");
elementstatus = elemToFind.isDisplayed() || elemToFind.isEnabled();
elemToFind.click();
} catch (NoSuchElementException e) {
report.updateTestLog("Element is not available", Status.FAIL);
}
采纳答案by Petr Jane?ek
Make absolutely sure you have imported org.openqa.selenium.NoSuchElementException
and NOT java.util.NoSuchElementException
.
绝对确保您已导入org.openqa.selenium.NoSuchElementException
而不是java.util.NoSuchElementException
.
Then it can't fail on the element missing. If it does, it probably fails with ElementNotVisibleException
which you can prevent by testing your elementStatus
before click()
ing.
然后它不能在缺少的元素上失败。如果是这样,它可能会失败ElementNotVisibleException
,您可以通过测试elementStatus
beforeclick()
来防止。
回答by Yash Jagdale
You can use
您可以使用
try
{
//Actions can be performed here
}
catch (RuntimeException ee)
{
if (ee.toString().contains("NoSuchElementException"))
{
//steps
}
}