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

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

问题描述

在 Selenium 1.x 或 2.x 中是否有任何方法可以滚动浏览器窗口,以便由 XPath 标识的特定元素在浏览器中可见?Selenium 中有一个 focus 方法,但它似乎并没有在 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天全站免登陆