Reputation: 17
driver.findElement(By.id("btnSendMailCopy")).click();
Thread.sleep(3000);
if(driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).isDisplayed())
{
driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).click();
System.out.println("clicked");
}
else if(driver.findElement(By.id("VendorCardHolderName")).isDisplayed())
{
Select dropdown = new Select(driver.findElement(By.id("VendorTinCardType")));
dropdown.selectByVisibleText("VISA");
driver.findElement(By.id("VendorCardHolderName")).sendKeys("TestName");
Without using if else i was able to run the script successfully but when I want to run else part its showing the error as
Unable to locate element: {"method":"xpath","selector":"/html/body/section[1]/div/article/nav/button[2]"}
Upvotes: 1
Views: 1036
Reputation: 688
try this
driver.findElement(By.id("btnSendMailCopy")).click();
Thread.sleep(3000);
if(driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).size()>0)
{
driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).click();
System.out.println("clicked");
}
else if(driver.findElements(By.id("VendorCardHolderName")).size()>0)
{
Select dropdown = new Select(driver.findElement(By.id("VendorTinCardType")));
dropdown.selectByVisibleText("VISA");
driver.findElement(By.id("VendorCardHolderName")).sendKeys("TestName");
}
It was failed due to that element you are checking at isDisplayed was not available. So to overcome that you have to write try/catch or the code I provide. They should work.
Upvotes: 0
Reputation: 3927
As per code if first element is displayed then go for code in if, if that first element is not displayed then go for code in else.
now simple thing here is, if the first element is not displayed then sure we will receive no element exception right? so we need handle this by try/catch.
Boolean dd;
try{
dd = driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).isDisplayed();
}catch(Exception e){
//you can print as element not displayed
}
then go for if condition
if(dd==true){
//do something
}else{
//do some thing else
}
Thank You, Murali
Upvotes: 1
Reputation: 17553
Try code as below:-
Boolean dd = driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).isDisplayed();
if(dd==true)
{
driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).click();
System.out.println("clicked");
}
else{
System.out.println("Element is not found");
}
Hope it will help you :)
Upvotes: 0