如何使用 Java 中的 Selenium WebDriver 向下滚动?

software testingautomation testingselenium web driverjava更新于 2024/7/1 22:50:00

我们可以使用 Selenium 向下滚动。Selenium 无法直接处理滚动。它需要 Javascript Executor 的帮助才能执行滚动操作直至元素。

首先,我们必须找到要滚动到的元素。接下来,我们将使用 Javascript Executor 运行 Javascript 命令。方法 executeScript 用于在 Selenium 中运行 Javascript 命令。我们将借助 Javascript 中的 scrollIntoView 方法,并将 true 作为参数传递给该方法。

语法

WebElement elm = driver.findElement(By.name("name"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",elm);

示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollAction{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm ");
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // 识别元素
      WebElement n=driver.findElement(By.xpath("//*[text()='Contact']"));
      // Javascript 执行器
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView
      (true);", n);
   }
}

输出


相关文章