How to handle if (element.display) in selenium

Viewed 319

I want to check if element is displayed - if true than execute some code. If not than execute some other code.

When I am trying to do that if the condition is false and the element does not exist then the test crush. Its not continue to the else or else if.

I want to know how to handle it.

In the next code I want to check if arrow side is up or down, if its up do something else do something different.

if (ca.arrowuppicknewaddress().isDisplayed())
    {
    
//  ca.arrowpicknewaddress().click();
//  Thread.sleep(2000);     
    driver.findElement(By.xpath("/html[1]/body[1]/div[5]/div[1]/div[2]/div[1]/section[1]/div[2]/div[1]/div[1]/section[1]/div[1]/ul[1]/li[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/span[1]")).click();
    Thread.sleep(1000);
//  ca.arrowpicknewaddress().click();
//  Thread.sleep(1000);
//  driver.findElement(By.xpath("/html[1]/body[1]/div[5]/div[1]/div[2]/div[1]/section[1]/div[2]/div[1]/div[1]/section[1]/div[1]/ul[1]/li[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[3]/div[1]/div[2]/div[1]/span[1]")).click();
//  Thread.sleep(3000);
    driver.findElement(By.xpath("//*[@id=\"deliveryScheduleModalData\"]/div[1]/button")).click();
    Thread.sleep(2000);
    ca.addOTC().click();
    Thread.sleep(2000);
    ca.PaymentToExendedCart().click();
    Thread.sleep(2000);
    ExtendedCart ec = new ExtendedCart(driver);
    ec.ToCheckOut().click();    
    }
     
    
        ca.arrowpicknewaddress().click();
        Thread.sleep(2000);     
        driver.findElement(By.xpath("/html[1]/body[1]/div[5]/div[1]/div[2]/div[1]/section[1]/div[2]/div[1]/div[1]/section[1]/div[1]/ul[1]/li[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/span[1]")).click();
        Thread.sleep(1000);

Can someone help me to make it correctly ?

Thanks in advance

1 Answers

Two ways :

1. List

You can get that element in a list using (findElements) and then if size is > 0 then execute your desire code or else if it is 0 then do the else part.

Code :

if (driver.findElements(By.xpath("Some xpath here")).size() > 0) {
   // execute if block here
}
else {
  // execute else block here
}

Benefit :

You will not have any exception. 

Cons :

Waiting time, let's say if element is not there then findElements will wait (ImplicitWait) to find it, so bit time consuming.

2. Do try-catch Instead :

try {
if(someWebElement.isDisplayed()){

}
catch(){
write the code if element is not found
}

}
Related