如何利用 Java 中的 Selenium 滾動瀏覽網頁?


我們可以利用 Java 中的 Selenium 滾動瀏覽網頁。Selenium 無法直接處理滾動。它藉助 Javascript 執行程式執行滾動操作直到某一個元素。

首先,我們必須找到需要滾動的目標元素。接下來,我們使用 Javascript 執行程式來執行 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.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollAction{
   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(4, TimeUnit.SECONDS);
      //launch application
      driver.get
      ("https://tutorialspoint.tw/about/about_careers.htm ");
      // identify element
      WebElement n=driver.findElement(By.xpath("//*[text()='Contact']"));
      // Javascript executor
      ((JavascriptExecutor)driver)
      .executeScript("arguments[0].scrollIntoView(true);", n);
   }
}

輸出

更新於: 2021-11-18

687 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告