如何在 Java 中使用 Selenium WebDriver 滾動頁面向上或向下?
我們可以使用 Java 在 Selenium webdriver 中滾動頁面向上或向下。這需要使用 Actions 類。首先,我們必須建立此 Actions 類的物件,然後應用 sendKeys 方法。
現在,要向下滾動頁面,我們必須將引數 Keys.PAGE_DOWN 傳遞給此方法。要再次向上滾動頁面,我們必須將引數 Keys.PAGE_UP 傳遞給 sendKeys 方法。最後,我們必須使用 build 和 perform 方法來執行此操作。
語法 −
Actions a = new Actions(driver); //scroll down a page a.sendKeys(Keys.PAGE_DOWN).build().perform(); //scroll up a page a.sendKeys(Keys.PAGE_UP).build().perform();
示例
程式碼實現
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.Keys;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class ScrollUpDownActions{
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");
// object of Actions class to scroll up and down
Actions at = new Actions(driver);
at.sendKeys(Keys.PAGE_DOWN).build().perform();
//identify element on scroll down
WebElement l = driver.findElement(By.linkText("Latest Courses"));
String strn = l.getText();
System.out.println("Text obtained by scrolling down is :"+strn);
at.sendKeys(Keys.PAGE_UP).build().perform();
//identify element on scroll up
WebElement m = driver.findElement(By.tagName("h4"));
String s = m.getText();
System.out.println("Text obtained by scrolling up is :"+s);
driver.quit();
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP