如何使用 Selenium WebDriver 中的 WebElement 座標在網頁中滾動?


我們可以使用 JavaScript Executor 使用 Selenuim WebDriver 中 webelement 的座標滾動網頁。Selenium 透過 executeScript 方法執行 JavaScript 命令。

要獲取元素的唯一座標,我們應該建立一個 Point 類的物件,該物件將儲存從 getLocation 方法獲取的 webelement 的位置。

然後,可以分別從 getX 和 getY 方法計算各個 x 和 y 座標值。最後,要真正執行滾動到元素座標,將命令 window.scrollBy(x 座標,y 座標) 作為引數傳遞給 executeScript 方法。

語法

(JavascriptExecutor)
driver).executeScript("window.scrollBy(100,150)");

此處,100 和 150 分別是 x 和 y 座標。

示例

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.Point;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollWithCodrdnts{
   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");
      //identify element
      WebElement n = driver.findElement(By.linkText("Latest Courses"));

      //obtain element x, y coordinates with getLocation method
      Point p = n.getLocation();
      int X = p.getX();
      int Y = p.getY();
      //scroll with Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript("window.scrollBy(" + X + ", " + Y + ");");
      System.out.println("Text is: " + n.getText());
      driver.quit();
   }
}

輸出

更新日期: 06-4 月-2021

3K+ 瀏覽量

開啟你的 職業

完成課程以獲得認證

開始
廣告