如何在 Selenium 中執行頁面滾動操作?
我們可以在 Selenium 中執行以下與滾動相關的操作 −
垂直滾動
向下滾動到特定畫素。
JavascriptExecutor j = (JavascriptExecutor) driver; // scroll down by 1500 pixel with coordinates 0 and 1500 in x, y axes j.executeScript("window.scrollBy(0,1500)");
向下滾動到頁面底部。
JavascriptExecutor j = (JavascriptExecutor) driver; // scroll down the bottom of page js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
示例
垂直向下滾動,直到元素可見。
import org.openqa.selenium.By; import org.openqa.selenium.Keys; 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 ScrollDownVisible { 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); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement terms = driver.findElement(By.linkText("Terms of use”)); // scroll down the web element for viewing js.executeScript("arguments[0].scrollIntoView();",terms); driver.close(); } }
水平滾動
示例
頁面上進行水平滾動。
import org.openqa.selenium.By; import org.openqa.selenium.Keys; 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 HScrollDown { 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); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement meets = driver.findElement(By.linkText("NetMeeting”)); // scroll down the web element for viewing js.executeScript("arguments[0].scrollIntoView();", meets); driver.close(); } }
廣告