0

I'm trying to automate a task through selenium that deletes a set of database tables.
The corresponding code is

WebElement element=null;
while((element = driver.findElement(By.name("db__button"))) != null){ driver.findElement(By.name("db__button")).click(); driver.findElement(By.name("ConfirmButton")).click(); }

However I'm getting the following error:-

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"name","selector":"db_vaults__button"} For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html

This runs fine as long as there are tables in the database but when there are no tables left then the GUI doesn't show any list (rightly so) and db__button is not present on the page and therefore By.name("db__button") is failing.
I guess there is something missing in this code which is trying to delete some tables in a loop.
The suggested link in the stack trace doesn't has any information.
Any Ideas?

Thanks.

Ankur
  • 11,239
  • 22
  • 63
  • 66

2 Answers2

2

You can do something like mentioned below:

try {
        element = driver.findElement(By.name("db__button"));
        driver.findElement(By.name("db__button")).click();
        driver.findElement(By.name("ConfirmButton")).click();
    } catch (NoSuchElementException e) {

    }

The above code will try to find your button and in case it is not found will throw an exception.You can write code(if any) inside the catch block when the element(db_button) is not found.

Varun Menon
  • 390
  • 1
  • 6
  • A better solution exist, have a look to this answer: http://stackoverflow.com/questions/6521270/webdriver-check-if-an-element-exists – Flanfl Oct 10 '12 at 14:35
0

There are several options. I recommend these. Create a method or web driver extension as below an use it.

    var elements = driver.FindElements(by);
    return (elements.Count >=1) ? elements.First() : null;

behnam shateri
  • 1,223
  • 13
  • 18