Java Selenium:模式内容中的按钮不可单击

Java Selenium:模式内容中的按钮不可单击,java,selenium,selenium-webdriver,xpath,css-selectors,Java,Selenium,Selenium Webdriver,Xpath,Css Selectors,我想在Selenium测试期间单击“OK”按钮,但元素不可见 driver.findelelement(By.xpath(“/*[@id=\”5f6e7b16-0fa1-4db6-869b-3a6ba6b0fafe\”))。单击(); 取消 好啊 我认为在DOM中,按钮id是动态变化的。每当重新加载页面时,它将生成新的id。在Selenium代码和HTML中使用的按钮id不同。因此,我建议您选择className。试试下面的代码,希望它对你有用 //If the Elemen

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

driver.findelelement(By.xpath(“/*[@id=\”5f6e7b16-0fa1-4db6-869b-3a6ba6b0fafe\”))。单击();

取消
好啊

我认为在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();

使用JavascriptExecutor单击元素

参考代码

WebElement element = driver.findElement(By.xpath("//*[@id=\"5f6e7b16-0fa1-4db6-869b-3a6ba6b0fafe\"]"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
根据您共享的HTML,所需元素似乎位于引导模式对话框中,并且元素的
id
属性是动态的。因此,要调用
click()
,您必须按如下方式引导WebDriverWait:

  • css选择器

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

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

Selenium没有单击不可见元素有什么解决方法吗?您可以插入Java脚本@塞迪,你能在模态中看到“Ok”按钮吗?或者不是。@BhavinDholakiya是的。欢迎您,如果您认为这是解决您的问题的最佳方案,您可以。@Ceddyy您能解释一下这段代码的问题吗?