如果进行任何更改,我正在使用java selenium来保存网页数据。
网页包含两个按钮'确认'和'取消'。如果我对网页进行了任何更改,则都会确认'和'取消'当我可以使用下面的代码点击确认按钮时,可以看到按钮。
WebElement confirm =wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(), 'Confirm')]")));
confirm.click();
如果网页没有变化,当我想点击取消按钮自动时,确认按钮将被禁用(灰色)。
我尝试使用以下代码,但它无效。请帮忙。
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();
}
答案 0 :(得分:1)
为什么要复杂化?保持简单。
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();
}
您也可以尝试使用confirm.isDisplayed();
答案 1 :(得分:0)
单击“确认”按钮失败后,您可以尝试捕获异常,作为异常处理的一部分,您可以通过以下方式单击“取消”按钮:
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();
}
更新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();
请告诉我,它是否适合您。