首页 > 解决方案 > Not able to click "Close" button of a Modal In Selenium Webdriver (Java)

问题描述

After clicking on a link a modal appear where a close button exist. I tried to close the modal with below code but it's not working.

WebElement element = driver1.findElement(By.className("btn btn-secondary"));

if (element.isEnabled()) {
  element.click();
} else {
  System.out.println("Disable");
}

标签: javaselenium-webdriver

解决方案


我可以从您的定位器中得知您至少遇到了错误,

不允许使用复合类名称

By.className()需要一个类名,但您提供了两个将导致上述错误。如果没有 HTML,很难说最好的定位器可能是什么,但可能有用的是 CSS 选择器,

By.cssSelector(".btn.btn-secondary")

尽管这是通用的,但匹配的元素可能不止一个。

您可能需要添加等待,特别是因为您正在处理模式对话框,

new WebDriverWait(driver).until(ExpectedConditions.elementToBeClickable(...)).click();

您可能需要再次等待以确保在脚本继续之前对话框关闭。


推荐阅读