【问题标题】:How to click on the Cancel button as per the html through Selenium and Java如何通过 Selenium 和 Java 根据 html 单击取消按钮
【发布时间】:2019-01-20 23:36:21
【问题描述】:

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']"}

【问题讨论】:

  • 您遇到什么错误?分享您尝试过的相关 HTML 和确切代码。
  • 按钮在&lt;frame&gt;标签内吗?
  • 提供的代码中的选择器与异常日志中的选择器不同...它们都不起作用

标签: java selenium xpath css-selectors webdriver


【解决方案1】:

这可能是时间问题。尝试等到所需的按钮出现在 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();

【讨论】:

  • 这是错误,我按照您的建议进行了修改。 org.openqa.selenium.WebDriverException:未知错误:元素 在点 (537 , 397)。其他元素会收到点击:
  • “保存”后会弹出一个对话框窗口 -> 单击“确定” -> 使用取消并保存返回旧窗口。焦点在保存,无法点击取消。
  • 所以取消按钮被禁用了?你目前的例外是什么?
  • 取消没有被禁用。它在那里,但重点是保存。
  • 如何将焦点转移到对话窗口。如果,我不保存并直接取消,这是可行的。 wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(@class, 'modal-footer-button') and text()='Cancel']"))).click();但是,如果我保存并单击 ok ,返回旧对话框并尝试单击取消,它不起作用
【解决方案2】:

试试这个

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

另外,放置一些等待元素定位

driver.manage().window().maximize();    
WebElement Cancelbtn= driver.findElement(By.xpath("//button[text()='Cancel']"));
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(Cancelbtn));
Cancelbtn.click();

【讨论】:

    【解决方案3】:

    根据 HTML,您已与 text 共享元素,因为 CancelModal 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();
      

    【讨论】:

    • 模态窗口有取消和保存。保存后弹出另一个窗口-。单击确定,返回模态窗口。现在,单击取消失败。如果,我不保存就取消,xpath 正在工作。
    • 您需要在问题中更新此信息。使用这行代码会发生什么?
    猜你喜欢
    • 2018-12-17
    • 2019-01-31
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多