如何通过Selenium和Java按html上的单击取消按钮

时间:2018-08-14 07:25:22

标签: java selenium xpath css-selectors webdriver

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:无此类元素:无法   定位元素:   {“方法”:“ xpath”,“选择器”:“ // button [@ type ='button'] [@ class ='modal-footer-button   g-capitalize btn btn-link'] [@ value ='Cancel']“}

3 个答案:

答案 0 :(得分:0)

尝试一下

student.getStudentCourse().getCourse()

另外,放置一些元素,直到找到

WebElement Cancelbtn= driver.findElement(By.xpath("//button[text()='Cancel']"));
Cancelbtn.click();

答案 1 :(得分:0)

这可能是计时问题。尝试等到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();

答案 2 :(得分:0)

根据 HTML ,您已与 text 共享元素,因为取消 Modal Window 中,因此您必须诱使 WebDriverWait 才能使所需的元素可点击,并且可以使用以下任一解决方案:

  • cssSelector

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.modal-footer-button.g-capitalize.btn.btn.link[type='button']"))).click();
    
  • xpath

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='modal-footer-button g-capitalize btn btn link' and contains(.,'Cancel')]"))).click();