【问题标题】:Selenium findElement throws exception when element present in page but not visible in viewport当元素存在于页面中但在视口中不可见时,Selenium findElement 会引发异常
【发布时间】:2020-03-27 14:19:07
【问题描述】:

当元素存在于 DOM 中并且在视口中可见时,以下代码可以完美运行:

WebElement button = webdriver.findElement(By.id("myButton"));

但是,我不明白为什么当按钮存在于 DOM 中但在视口中不可见时它会引发异常。

我确定该按钮存在:这里没有 ajax 在起作用。

如何测试是否存在于 DOM 中的元素是否在视口中可见?

我已经在 stackoverflow 上看到了一些有用的链接:

https://stackoverflow.com/a/44916498/420593

How to check if an element is into view using Selenium WebDriver?

【问题讨论】:

  • 你试过显式等待吗?
  • yes ` WebDriverWait wait = new WebDriverWait(webdriver, 3);wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("myButton")));` 但没有任何结果。
  • 网址可以公开访问吗?

标签: java selenium


【解决方案1】:

您可以使用 WebDriverWait 和 action 类来移动到元素并执行点击它。

WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement button = wait.until(
        ExpectedConditions.elementToBeClickable(By.id("myButton")));
Actions actions = new Actions(driver);
actions.moveToElement(button).click().build().perform();

【讨论】:

    【解决方案2】:

    经过更多研究,这是我的结论:

    webdriver.executeScript("arguments[0].scrollIntoView()", button);
    button.click();
    

    应该可以,但在我的情况下,由于一些引导程序固定标题,按钮在视图中但被固定标题隐藏在它上面(z-index)。并在执行第二行时抛出异常。

    以下情况同样如此:

    Actions actions = new Actions(driver);
    actions.moveToElement(button).click().build().perform();
    

    所以,我终于通过在javascript中模拟点击解决了我的问题:

    webdriver.executeScript("arguments[0].scrollIntoView()", button);
    

    【讨论】:

      猜你喜欢
      • 2018-05-18
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多