seleniumwebdriver——JS滚动到指定位置
1.DOM滚动⽅法
1、scrollIntoView(alignWithTop)  滚动浏览器窗⼝或容器元素,以便在当前视窗的可见范围看见当前元素。如果alignWithTop为true,或者省略它,窗⼝会尽可能滚动到⾃⾝顶部与元素顶部平齐。-------⽬前各浏览器均⽀持
2、scrollIntoViewIfNeeded(alignCenter) 只在当前元素在视窗的可见范围内不可见的情况下,才滚动浏览器窗⼝或容器元素,最终让当前元素可见。如果当前元素在视窗中可见,这个⽅法不做任何处理。如果将可选参数alignCenter设置为true,则表⽰尽量将元素显⽰在视窗中部(垂直⽅向)------Safari、Chrome实现了这个⽅法
3、scrollByLines(lineCount) 将元素的内容滚动指定的⾏数的⾼度,lineCount的值可以为正值或是负值。---Safari、Chrome实现了这个⽅法
4、scrollByPages(pageCount) 将元素的内容滚动指定的页⾯的⾼度,具体⾼度由元素的⾼度决定。---Safari、Chrome实现了这个⽅法
scrollIntoView()和scrollIntoVIewIfNeeded()作⽤的是元素的窗⼝,⽽scrollByLines()、scrollByPages()影响
元素⾃⾝,下⾯是⼏个⽰例:
//将页⾯主体滚动5⾏
document.body.scrollByLines(5);
//确保当前元素可见
//确保只在当前元素不可见的情况下才使其可见
//将页⾯主体往回滚1页
doument.body.scrollByPages(-1);
由于只有scrollIntoView被各浏览器均⽀持,所以这个⽅法最为常⽤。
2.滚动到指定位置
为啥使⽤滚动?因为如果页⾯没有完全显⽰,element如果是在下拉之后才能显⽰出来,只能先滚动到该元素才能进⾏click,否则是不能click操作JavascriptExecutor js=(JavascriptExecutor)driver;
// roll down and keep the element to the center of browser
其中e为指定位置元素定位.⽐如:driver.findElement(By.xpath(".//*[@id='page']/a[10]"))
可以封装滚动到元素的⽅法
/**
* @author hjianhui
* @param element
*/
public void scrollToElement(By by) {
WebElement e = findElement(driver, by);
log.info("scroll view element");
JavascriptExecutor js = (JavascriptExecutor) driver;
// roll down and keep the element to the center of browser
}
打开百度,搜索selenium,向下滑动点击下⼀页,代码如下:
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
selenium xpath定位import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
stng.Assert;
/**
* @author Hjianhui
* JavaScript.java  2016-08-04
*
*/
public class testScrollToElement{
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try{
<("www.baidu");
JavascriptExecutor driver_js= (JavascriptExecutor) driver;
//利⽤js代码键⼊搜索关键字
uteScript("ElementById(\"kw\").value=\"selenium\"");
driver.findElement(By.id("su")).click();
//等待元素页⾯加载
waitForElementToLoad(driver, 10, By.xpath(".//*[@id='container']/div[2]/div/div[2]"));
//向下滑动直到到元素下⼀页
uteScript("arguments[0].scrollIntoView(true)",driver.findElement(By.xpath(".//*[@id='page']/a[10]")));
driver.findElement(By.xpath(".//*[@id='page']/a[10]")).click();
}catch (Exception e){
e.printStackTrace();
}
driver.quit();
}
/**
* 在给定的时间内去查元素,如果没到则超时,抛出异常
* */
public static void waitForElementToLoad(WebDriver driver, int timeOut, final By By) { try {
(new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) {
WebElement element = driver.findElement(By);
return element.isDisplayed();
}
});
} catch (TimeoutException e) {
Assert.fail("超时!! " + timeOut + " 秒之后还没到元素 [" + By + "]");
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。