Selenium 纵向滚动条控制
页面异步加载时,为了获取由浏览器滚动条触底加载新的内容时,需要用到webdriver来控制滚动条。
第一种方式:直接控制滚动条跳转到具体位置
@Test
public void scrollBarPositionTest() {
webDriver.get("https://www.taobao.com/");
JavascriptExecutor javascriptExecutor = ((JavascriptExecutor) webDriver);
//这里执行原生js代码滚动纵向移动(0,y)document.body.scrollHeight这么多个高度
javascriptExecutor.executeScript("window.scrollTo(0,document.body.scrollHeight)");
//测试当前页面的滚动条高度
Object y = javascriptExecutor.executeScript("return document.body.scrollHeight");
logger.debug("y.class:{},y:{}",y.getClass().getName(),y);
//do something
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
第二种方式:显示页面中已经加载,但屏幕上无法显示的元素
private List<WebElement> loadingAllArticles(int lastSize) {
List<WebElement> webArticles = webDriver.findElements(By.cssSelector("#app > div > div.main-wrapper > div.content-list > div > div"));
int curSize = webArticles.size();
if (curSize == 0 || lastSize == curSize) {
return webArticles;
}
JavascriptExecutor jsExecutor = (JavascriptExecutor) webDriver;
//屏幕移动到webArticles 数据的最后一项(已经加载但未显示到当前窗口),变相控制滚动条
jsExecutor.executeScript("arguments[0].scrollIntoView(true);", webArticles.get(curSize - 1));
loading(5);
return loadingAllArticles(curSize);
}
Selenuim js赋值问题
JavascriptExecutor jsExecutor = (JavascriptExecutor) webDriver;
long lastScrollHeight = (Long) jsExecutor.executeScript("return document.body.scrollHeight");
//ES6语法,复制
jsExecutor.executeScript("(scrollHeight) => window.scrollTo(0,scrollHeight)", lastScrollHeight);
JavascriptExecutor jsExecutor = (JavascriptExecutor) webDriver;
//内置参数arguments复制,[0]为下标
jsExecutor.executeScript("arguments[0].scrollIntoView(true);", webArticles.get(curSize - 1));