How to continue webdriver/selenium after error

不想你离开。 提交于 2020-01-06 04:05:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!