如何在 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.tw/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