Selenium | 滚动

使用场景

如果你遇到以下情况,可以尝试使用滚动条滚动:

需要滚动到指定元素所在位置

(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();
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值