使用 webdriver 滚动到元素。
我们可以使用 Selenium webdriver 向某个元素执行滚动。这可以通过多种方式实现。Selenium 不能直接处理滚动。它借助Javascript 执行器和 Actions 类执行滚动操作。
首先,我们必须找到要滚动到的元素,可以使用类、ID、名称等定位器。接下来,我们将借助 Javascript 执行器来运行 Javascript 命令。executeScript 方法用于在 Selenium 中执行 Javascript 命令。我们必须在 Javascript 中使用 scrollIntoView 方法,并将**true** 作为参数传递给该方法。
语法
WebElement e = driver.findElement(By.name("name"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", e);示例
使用 Javascript 执行器的代码实现。
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 ScrollToElementJs{
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://tutorialspoint.com/index.htm");
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// identify element
WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
// Javascript executor
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView (true);", m);
Thread.sleep(200);
driver.close();
}
}使用 Actions 类,我们将使用 moveToElement 方法,并将 webelement 定位器作为参数传递给该方法。
示例
使用 Actions 的代码实现。
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.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class ScrollToElementActions{
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://tutorialspoint.com/index.htm");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
// moveToElement method with Actions class
Actions act = new Actions(driver);
act.moveToElement(m);
act.perform();
driver.close();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP