如何在 Selenium Webdriver 中向下或向上滚动一个页面?
我们可以使用 JavaScript Executor 在 Selenium webdriver 中向下或向上滚动页面。Selenium 可以使用 executeScript 方法来执行 JavaScript 命令。
若要在页面中垂直向下滚动,我们必须使用 JavaScript 命令 window.scrollBy 。然后将像素值传递给 x 轴和 y 轴,以分别用于水平和垂直滚动。
为 x 轴设置的正值将使页面向右滚动,而为 x 轴设置的负值将使页面向左滚动。类似地,为 y 轴设置的正值将使页面向下滚动,而为 y 轴设置的负值将使页面向上滚动。
语法
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("window.scrollBy(0,500)");
j.executeScript("window.scrollBy(0,-500)");示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollUpDown{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/index.htm");
// scroll down by 500 pixels with Javascript Executor
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("window.scrollBy(0,500)");
// identify element
WebElement m = driver.findElement(By.linkText("Latest Courses"));
String s = m.getText();
System.out.println("Text obtained on scrolling down: "+ s);
// scroll down up 500 pixels with Javascript Executor
j.executeScript("window.scrollBy(0,-500)");
// identify element
WebElement n = driver.findElement(By.tagName("h4"));
String r = n.getText();
System.out.println("Text obtained on scrolling up: "+ r);
driver.quit();
}
}输出

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