问题
I'm doing a test bot with webdriver. I have a scenario where it clicks on a button, a new windows open, and it searches for an element by a specific xpath, but sometimes there is no such element because it can be disabled and i get this error: org.openqa.selenium.NoSuchElementException. How can i bypass it/continue the bot so it just closes the new windows if it doesn't find the element with that xpath and just continue with the code?
回答1:
In 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
}
回答2:
You need to surround the click event with a try/catch statement, and inside the catch statement check if the exception is the one you are trying to bypass:
try {
driver.findElement(by).click();
} catch(Exception e) {
if ( !(e instanceof NoSuchElementException) ) {
throw e;
}
}
来源:https://stackoverflow.com/questions/37399391/how-to-continue-webdriver-selenium-after-error