Reputation: 35
I am using java selenium for saving web data if any changes made.
Web page contains two buttons 'Confirm' and 'Cancel'. If i made any changes in web page, both 'confirm' and 'cancel' buttons will be visible at the time i can click confirm button by using below code .
WebElement confirm =wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(), 'Confirm')]")));
confirm.click();
If there is no changes in web page , Confirm button will get disabled(grayed) at the time i want to click Cancel button Automatically.
I have tried with below code , it is not working. Please help on this.
try
{
WebElement confirm = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(), 'Confirm')]")));
confirm.click();
}
catch (ElementNotVisibleException exception)
{
WebElement cancel = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(), 'Cancel')]")));
cancel.click();
}
Upvotes: 0
Views: 100
Reputation: 910
You can try catching the exception when click on 'Confirm' button fails and as part of exception handling you can click on 'Cancel' button in following way:
try {
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(), 'Confirm')]")));
driver.findElement(By.xpath("//button[contains(text(), 'Confirm')]")).click();
} catch (Exception we) {
System.out.println("'Confirm' button is not clickable, hence trying to click on 'Cancel' button");
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(), 'Cancel')]")));
driver.findElement(By.xpath("//button[contains(text(), 'Cancel')]")).click();
}
UPDATE 1:
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//button[contains(text(), 'Confirm')]")));
WebElement confirmButton = driver.findElement(By.xpath("//button[contains(text(), 'Confirm')]"));
if (confirmButton.isEnabled())
confirmButton.click();
else
driver.findElement(By.xpath("//button[contains(text(), 'Cancel')]")).click();
Let me know, whether it works for you.
Upvotes: 0
Reputation: 492
Why do you want to complicate things? Keep it simple.
WebElement confirm = driver.findElement(By.id("<your confirm button id>"));
WebElement cancel= driver.findElement(By.id("<your cancel id>"));
if(confirm.isEnabled())
{
confirm.click();
}
else
{
cancel.click();
}
You may also try with confirm.isDisplayed();
Upvotes: 1