首页 > 解决方案 > 如何通过 Selenium 和 Java 根据 html 单击取消按钮

问题描述

HTML:

<button type="button" class="modal-footer-button g-capitalize btn btn link">Cancel</button>

代码试用:

By.xpath("//button[@type='button']").click()

没用。

也尝试了许多其他方法。无法单击取消按钮。错误:

org.openqa.selenium.NoSuchElementException: 没有这样的元素: 无法定位元素: {"method":"xpath","selector":"//button[@type='button'][@class='modal-footer -button g-capitalize btn btn-link'][@value='Cancel']"}

标签: javaseleniumxpathcss-selectorswebdriver

解决方案


这可能是时间问题。尝试等到所需的按钮出现在 DOM 中:

WebDriverWait wait = new WebDriverWait(driver, 10);

wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@class='fade modal' and @role='dialog']")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(@class, 'modal-footer-button') and text()='Cancel']"))).click();

推荐阅读