ISTQB Certified Software Test Engineer

Thursday, May 2, 2013

Element Not Present in Selenium Webdriver

Some times when we are automating the applications using web driver,we need to check whether an element is present or not.If it is present a particular method has to be called,if the element is not present another method has to be called.

For example In User Profile page if user has permissions to edit,editProfile script should be called,if user doesn't have permissions to edit viewProfile should be called.

But in webdriver if element appears then it will work fine,if it is not present then it will directly throw an exception(ElementNotFound or NoSuchElement).If it throws an exception,this should be handled, we need to call viewProfile method as per the above example in CatchBlock.

If we have same kind of scenario for some other element then we need to call that as well in catch block which is not a good solution.

So to handle this type of scenarios we need to write an user defined generic function which can verify an element is present or not.

Simply call the above method in test method of your script

if element is present if goes in one flow,else it takes another flow

1 comment:

  1. public Boolean isElementExistsOnPage(String xpath) {
    try {
    return true;
    } catch (NoSuchElementException e) {
    return false;

    public Boolean isElementExistsOnPage(String xpath) {
    List elements = driver.findElements(By.xpath(xpath));
    if (elements.size() == 0) {
    return false;
    } else {
    return true;