【问题标题】:Selenium: Button in modal content is not clickableSelenium:模式内容中的按钮不可点击
【发布时间】:2018-10-07 19:38:44
【问题描述】:

我想在 Selenium 测试期间单击“确定”按钮,但元素不可见。

 driver.findElement(By.xpath("//*[@id=\"5f6e7b16-0fa1-4db6-869b-3a6ba6b0fafe\"]")).click();
<div class="bootstrap-dialog-footer-buttons">
    <button class="btn btn-default" id="5a4bb849-7a61-4603-9ef2-f9e0ecab4523">
        <span class="glyphicon glyphicon-ban-circle"></span> Cancel
    </button>
    <button class="btn btn-warning" id="f7f4b18b-2ba2-4c1e-b541-a254c080f398">
        <span class="glyphicon glyphicon-ok"></span> Ok
    </button>
</div>

【问题讨论】:

  • Selenium 不会点击不可见的元素
  • 有什么解决办法吗?
  • 可以注入Java Script!
  • @ceddyy,你能在模态中看到“确定”按钮吗?与否。
  • @BhavinDholakiya 是的。

标签: java selenium selenium-webdriver xpath css-selectors


【解决方案1】:

根据您分享的 HTML,似乎所需的元素位于 Bootstrap 模式对话框 中,并且该元素的 id 属性是动态的。因此,要调用 click(),您必须按如下方式诱导 WebDriverWait

  • cssSelector

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.bootstrap-dialog-footer-buttons button.btn.btn-warning"))).click();
    
  • xpath

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='bootstrap-dialog-footer-buttons']//button[@class='btn btn-warning']"))).click();
    

【讨论】:

    【解决方案2】:

    使用JavascriptExecutor点击元素,

    参考代码,

    WebElement element = driver.findElement(By.xpath("//*[@id=\"5f6e7b16-0fa1-4db6-869b-3a6ba6b0fafe\"]"));
    JavascriptExecutor executor = (JavascriptExecutor)driver;
    executor.executeScript("arguments[0].click();", element);
    

    【讨论】:

    • @ceddyyy 你能解释一下这段代码有什么问题吗?
    【解决方案3】:

    我认为在您的 DOM 中,按钮 ID 是动态变化的。每当页面重新加载时,它都会生成新的 id。您在 Selenium 代码和 HTML 中使用了不同的按钮 ID。所以,我建议你选择className。试试下面的代码,希望它对你有用。

            //If the Element is not visible then wait until that element is not visible
            new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.className("btn btn-warning")));
    
            //If the element is visible but not Clickable then wait until that element get Clickable.       
            new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.className("btn btn-warning")));
    
            //Then simply click the button
            driver.findElement(By.className("btn btn-warning")).click();
    

    【讨论】:

    • 欢迎您,如果您认为这是解决您问题的最佳方案,您可以accept the answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多