使用 webdriver 滾動到元素。
我們可以使用 Selenium webdriver 向某個元素執行滾動。這可以透過多種方式實現。Selenium 不能直接處理滾動。它藉助Javascript 執行器和 Actions 類執行滾動操作。
首先,我們必須找到要滾動到的元素,可以使用類、ID、名稱等定位器。接下來,我們將藉助 Javascript 執行器來執行 Javascript 命令。executeScript 方法用於在 Selenium 中執行 Javascript 命令。我們必須在 Javascript 中使用 scrollIntoView 方法,並將**true** 作為引數傳遞給該方法。
語法
WebElement e = driver.findElement(By.name("name"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", e);示例
使用 Javascript 執行器的程式碼實現。
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 ScrollToElementJs{
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://tutorialspoint.tw/index.htm");
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// identify element
WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
// Javascript executor
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView (true);", m);
Thread.sleep(200);
driver.close();
}
}使用 Actions 類,我們將使用 moveToElement 方法,並將 webelement 定位器作為引數傳遞給該方法。
示例
使用 Actions 的程式碼實現。
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.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class ScrollToElementActions{
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://tutorialspoint.tw/index.htm");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement m=driver.findElement(By.xpath("//*[text()='Careers']"));
// moveToElement method with Actions class
Actions act = new Actions(driver);
act.moveToElement(m);
act.perform();
driver.close();
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP