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

What is the best way to scroll to a web element located on the current page within the viewport using Selenium

我是自动化新手,我想知道如何使用 selenium 和 java.

滚动到当前页面上的 Web 元素

我已经尝试了很多Whosebug中描述的方法。但是无法解决我的问题。

我尝试过的解决方案:

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

使用 Selenium[= 在 Viewport 当前页面上滚动 WebElement 24=] 你需要引入 WebDriverWait 来获取位于 元素的 可见性,你可以使用以下解决方案:

WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.id("id_of_element")));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element)

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

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));
}

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

WebDriverWait wait = new WebDriverWait(driver, 60);

希望对您有所帮助。

您正在将该元素从 javascript 传递到 java 然后返回到 javascript。 这是个坏主意,当它进行往返时,它可能已经不存在了。

((JavascriptExecutor) driver).executeScript("document.querySelector('#id_of_element').scrollIntoView(true);");

另外,很多你需要滚动到视图中的东西(使用旧的 seleniums),你不再这样做了。