如何在 Selenium 中实现页面滚动操作?
software testingautomation testingselenium web driver
在 Selenium 中,我们可以执行以下与滚动相关的操作:
垂直滚动
向下滚动到指定像素。
JavascriptExecutor j = (JavascriptExecutor) driver;
// 在 x 轴和 y 轴坐标 0 和 1500 处向下滚动 1500 像素
j.executeScript("window.scrollBy(0,1500)");
向下滚动到页面底部。
JavascriptExecutor j = (JavascriptExecutor) driver;
// 向下滚动页面底部
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://www.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”));
// 向下滚动网页元素即可查看
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://www.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”));
// 向下滚动网页元素即可查看
js.executeScript("arguments[0].scrollIntoView();", meets);
driver.close();
}
}

