出错后如何继续webdriver/selenium
How to continue webdriver/selenium after error
我正在用 webdriver 做一个测试机器人。我有一个场景,它点击一个按钮,一个新的 windows 打开,它通过特定的 xpath 搜索一个元素,但有时没有这样的元素,因为它可以被禁用,我得到这个错误:org.openqa.selenium.NoSuchElementException。我如何绕过 it/continue 机器人,如果它没有找到具有该 xpath 的元素并继续执行代码,它只会关闭新的 windows?
在 Java 中:
List<WebElement> foundElement = driver.findElements(By.xpath("<x-path of your element>"));
if (foundElement.size() > 0)
{
// do whatever you want to do in **presence** of element
} else {
// do whatever you want to do in **absence** of element
}
您需要用 try/catch 语句包围点击事件,并在 catch 语句中检查异常是否是您试图绕过的异常:
try {
driver.findElement(by).click();
} catch(Exception e) {
if ( !(e instanceof NoSuchElementException) ) {
throw e;
}
}
我正在用 webdriver 做一个测试机器人。我有一个场景,它点击一个按钮,一个新的 windows 打开,它通过特定的 xpath 搜索一个元素,但有时没有这样的元素,因为它可以被禁用,我得到这个错误:org.openqa.selenium.NoSuchElementException。我如何绕过 it/continue 机器人,如果它没有找到具有该 xpath 的元素并继续执行代码,它只会关闭新的 windows?
在 Java 中:
List<WebElement> foundElement = driver.findElements(By.xpath("<x-path of your element>"));
if (foundElement.size() > 0)
{
// do whatever you want to do in **presence** of element
} else {
// do whatever you want to do in **absence** of element
}
您需要用 try/catch 语句包围点击事件,并在 catch 语句中检查异常是否是您试图绕过的异常:
try {
driver.findElement(by).click();
} catch(Exception e) {
if ( !(e instanceof NoSuchElementException) ) {
throw e;
}
}