首页 > 解决方案 > 使用 Selenium 在视口内滚动到位于当前页面上的 Web 元素的最佳方法是什么

问题描述

我是自动化的新手,我想知道如何使用 selenium 和 java 滚动到当前页面上的 web 元素。

我尝试了许多在 stackoverflow 中描述的方法。但无法解决我的问题。

我尝试过的解决方案:

WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);

标签: javaseleniumselenium-webdriverwebdriverwebdriverwait

解决方案


您可以使用Selenium 提供的Actions类。

public void scrollToElement(WebElement element){
    Actions actions = new Actions(driver);
    actions.moveToElement(element);
    actions.perform();
    WebDriverWait wait = new WebDriverWait(driver, 60);
    wait.until(ExpectedConditions.visibilityOf(element));
}

在这里,我添加了一个显式等待,它将一直等到 web 元素可见。最长等待时间为 60 秒。如果 web 元素在 60 秒内不可见,则会引发异常。您可以通过更改此行来增加等待时间。

WebDriverWait wait = new WebDriverWait(driver, 60);

希望这可以帮助。


推荐阅读