使用 Selenium 將元素滾動到檢視中。
我們可能需要對頁面可視區域中不存在的元素執行操作。我們需要向下滾動頁面以到達該元素。
Selenium 無法直接執行滾動操作。這可以透過 Javascript 執行器 和 Selenium 中的動作類 來實現。DOM 可以藉助 Javascript 操作網頁上的所有元素。
Selenium 可以藉助 **execute_script()** 方法執行 Javascript 中的命令。對於 Javascript 解決方案,我們必須將 true 值傳遞給 **scrollIntoView()** 方法以識別頁面上我們當前位置下方的物件。我們可以藉助 Selenium 中的動作類執行滑鼠移動。
示例
使用 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 ScrollToViewJs{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://tutorialspoint.tw/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element WebElement l=driver.findElement(By.xpath("//*[text()='ABOUT US']")); // Javascript executor ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", l); Thread.sleep(800); driver.quit(); } }
在使用動作類滾動到檢視時,我們必須使用 moveToElement() 方法。此方法將執行滑鼠移動,直到元素的中間位置。
示例
使用動作類的程式碼實現。
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 ScrollToViewActions{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://tutorialspoint.tw/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element WebElement l=driver.findElement(By.xpath("//*[text()='ABOUT US']")); // Actions class with moveToElement() Actions a = new Actions(driver); a.moveToElement(l); a.perform(); driver.quit(); } }
輸出
廣告