使用场景
如果你遇到以下情况,可以尝试使用滚动条滚动:
需要滚动到指定元素所在位置
(1)点击元素时报错:
org.openqa.selenium.WebDriverException: unknown error: Element is not clickable
(2)滚动到指定元素位置,以进行其他操作。
需要滚动到指定坐标位置
(1)滚动到指定坐标。
(2)滚动到页面顶部或底部。
滚动方法
1. 使用JS脚本
Element.scrollIntoView();
使用场景:滚动到指定元素所在的位置。
详细文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView
使用示例:
//JS代码
$('#kb_block > b').get(0).scrollIntoView();
//Java代码
JavascriptExecutor executor = (JavascriptExecutor) driver;
WebElement e = driver.findElement(By.cssSelector("#kb_block > b"));
executor.executeScript("arguments[0].scrollIntoView();", e);
Element.scrollIntoViewIfNeeded()
【不推荐:部分浏览器不支持】
说明:此方法是标准的Element.scrollIntoView()方法的专有变体。
使用场景:滚动到指定元素所在的位置。
详细文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoViewIfNeeded
使用示例:同上,略。
window.scrollTo(x,y)
使用场景:滚动到指定坐标所处的位置。
详细文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/scrollTo
使用示例:
//JS代码
var x = $('#kb_block > b').offset().left;
var y = $('#kb_block > b').offset().top;
window.scrollTo(x,y);
//Java代码
JavascriptExecutor executor = (JavascriptExecutor) driver;
Point point = driver.findElement(By.cssSelector("#kb_block > b")).getLocation();
executor.executeScript("window.scrollTo(arguments[0],arguments[1]);", point.x, point.y);
使用扩展:
//滚动到页面顶部
window.scrollTo(0,0);
//滚动到页面底部
window.scrollTo(0,100000);
//滚动到可视区域中间部分
var e = $('#testid').get(0);
scrollIntoViewCenter(e);
function scrollIntoViewCenter(e){
//滚动元素到可视区域
e.scrollIntoView();
//元素顶端到可见区域顶端的距离
var top = e.getBoundingClientRect().top;
//浏览器可见区域高度
var height = document.documentElement.clientHeight;
//计算滚动到可视区域中间部分的纵轴偏移量
var yoffset = top - height/2;
//相对滚动
window.scrollBy(0,yoffset);
}
延伸阅读:
相对当前位置滚动:window.scrollBy()、Window.scrollByLines()、Window.scrollByPages()
2. 使用Actions类
使用场景:滚动到指定元素所在位置。
使用示例:
driver.get("https://gitee.com/");
WebElement e = driver.findElement(By.cssSelector("#git-footer-main div.qrcode.weixin > img"));
Actions actions = new Actions(driver);
actions.moveToElement(e).build().perform();