0

Can someone help me fixing NoSuchElementException. Let me explain what I am trying to do.

I am trying to login into an application with multiple sets of data. Lets say,

1) Valid username and password.

2) Valid username and invalid password.

Now what's happening is, I am trying to find element is present or not.

In my first case, element is present as user successfully loggedIn. But in my second case, user is not logged in and i am trying to find element present inside application after login.

Can any one tell me how to find a solution for such situation ?

wd.findElement(By.id("username")).sendKeys(UserName);
wd.findElement(By.id("password")).sendKeys(Password);
webElement.sendKeys(Keys.ENTER);
try
{
  Boolean ispresent =   wd.findElement(By.xpath("//div[@id='service_panel']")).isDisplayed();
  if(ispresent)
  {
   //doing something.
  }
}
catch(Exception e)
{
  e.printStackTrace();
}
1

Solution : Write one method for element present or not and call it.

1]

Method :

public static boolean checkElementPresent(WebElement webe)
{
    try
    {
        if(webe.isDisplayed())
        {
           //doing something.
        }
        return true;
    }
    catch (Exception e)
    {
        return false;
    }
}

Just call below line in your code :

Boolean ispresent = checkElementPresent(wd.findElement(By.xpath("//div[@id='service_panel']")));
if(ispresent)
{
        //doing something.
}
else
{
        // Do something
}

2]

Another Solution is :

try
{
      Boolean ispresent = 
      wd.findElement(By.xpath("//div[@id='service_panel']")).isDisplayed();
      if(ispresent)
      {
        //doing something.
       }
       else
       {
        // Do something
       }
}
catch(Exception e)
{
   // Do something
}

Reason : isDisplayed() method throws exception if element is not present in HTML DOM.

  • Thanks for your reply Sagar. I tried verifying url and got the solution. Appreciate for your help. – srikanth May 31 '17 at 8:01
0

Try this :

if(!driver.findElements(By.id("<id-of-the-element>")).size>0){
 //then do your normal operation
}
else{
//do something else
}
  • Thanks for your time Mayank. I tried verifying url and got the solution. Appreciate for your help. – srikanth May 31 '17 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.