如何在 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.com/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.com/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(); } }
广告