使用Selenium将元素滚动到视图中 [英] Scroll Element into View with Selenium

查看:106
本文介绍了使用Selenium将元素滚动到视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Selenium 1.x或2.x中是否有任何方法可以滚动浏览器窗口,从而使XPath标识的特定元素位于浏览器的视野中? Selenium中有一个聚焦方法,但在FireFox中似乎并没有实际滚动视图.有人对如何执行此操作有任何建议吗?

Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus method in Selenium, but it does not seem to physically scroll the view in FireFox. Does anyone have any suggestions on how to do this?

我需要这样做的原因是我正在测试页面上某个元素的点击.不幸的是,除非该元素可见,否则该事件似乎不起作用.我无法控制单击元素时触发的代码,因此无法调试或对其进行修改,因此,最简单的解决方案是将项目滚动到视图中.

The reason I need this is I'm testing the click of an element on the page. Unfortunately the event doesn't seem to work unless the element is visible. I don't have control of the code that fires when the element is clicked, so I can't debug or make modifications to it, so, easiest solution is to scroll the item into view.

推荐答案

在滚动方面已经尝试了很多方法,但是下面的代码提供了更好的结果.

Have tried many things with respect to scroll, but the below code has provided better results.

这将滚动直到该元素出现在视图中:

This will scroll until the element is in view:

WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500); 

//do anything you want with the element

这篇关于使用Selenium将元素滚动到视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆