首頁  >  文章  >  Java  >  如何使用Java中的Selenium WebDriver向下滾動?

如何使用Java中的Selenium WebDriver向下滾動?

WBOY
WBOY轉載
2023-08-20 16:41:281165瀏覽

我們可以使用Selenium向下滾動。 Selenium無法直接處理捲動操作,它需要藉助Javascript Executor來執行捲動操作,直到捲動到指定元素。

首先,我們需要定位到要捲動到的元素。接下來,我們將使用Javascript Executor來執行Javascript命令。在Selenium中,使用executeScript方法來執行Javascript指令。我們將藉助Javascript中的scrollIntoView方法,並將true作為參數傳遞給該方法。

語法

WebElement elm = driver.findElement(By.name("name"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",elm);

Example

的中文翻譯為:

範例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollAction{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm ");
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement n=driver.findElement(By.xpath("//*[text()='Contact']"));
      // Javascript executor
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView
      (true);", n);
   }
}

輸出

如何使用Java中的Selenium WebDriver向下滚动?##

以上是如何使用Java中的Selenium WebDriver向下滾動?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除