java - 使用 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);
解决方案
您可以使用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);
希望这可以帮助。
推荐阅读
- php - 将变量从一个函数传递到同一控制器中的另一个函数
- java - Eclipse 在 Windows10 中安装时返回错误消息
- android - 在 react-native 应用程序的发布版本中获取错误
- visual-studio-code - VS Code - 一个文件夹中的多个源文件
- python - 如何进行流畅的图像运动?| 基维
- python - Python获取div标签下的href
- jquery - 具有延迟和页面调整大小的 J-query 动画
- python - Selenium 找不到元素
- kubernetes - 如何在 Prometheus 中推送 Kubernetes 指标而不是拉取?
- unix - 为什么我不能重用管道与多个子进程通信?