Selenium,你如何检查滚动位置 [英] Selenium, how do you check scroll position
问题描述
在java中使用selenium,我需要测试一个返回顶部按钮,所以我做的是向下滚动页面,直到显示返回顶部按钮(当滚动页面的25%时显示) )并单击它,此按钮将用户带到页面顶部,现在我需要检查它是否有效,可见部分是页面的顶部。我怎么能用java做这个?
Using selenium with java, I need to test a "Back to top" button, so what I did is to scroll page down until "Back to top" button is shown (as it is shown when scrolled 25% of the page) and click it, this button takes user to the top of the page, now I need to check that it worked and the visible part is the top of the page. How can I do this using java?
推荐答案
一般原则是检查窗口的值。浏览器中的pageYOffset
。如果您的按钮完全回滚到顶部,则 window.pageYOffset
的值应为0.假设驱动程序
变量保存您的 WebDriver
实例:
The general principle is to check the value of window.pageYOffset
in the browser. If your button scrolls completely back to the top then window.pageYOffset
should have a value of 0. Assuming the driver
variable holds your WebDriver
instance:
JavascriptExecutor executor = (JavascriptExecutor) driver;
Long value = (Long) executor.executeScript("return window.pageYOffset;");
然后您可以检查值
是否为0 。 executeScript
用于在浏览器中运行JavaScript代码。
You can then check that value
is 0. executeScript
is used to run JavaScript code in the browser.
这个答案最初提到 scrollY
但IE上没有支持它。 上面的MDN页面说:
This answer initially mentioned scrollY
but there's no support for it on IE. The MDN page on it, says:
对于跨浏览器兼容性,请使用
window.pageYOffset
而不是window.scrollY
。此外,旧版本的Internet Explorer(< 9)不支持任何属性,必须通过检查其他非标准属性来解决。完全兼容的示例:
For cross-browser compatibility, use
window.pageYOffset
instead ofwindow.scrollY
. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example:
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft;
var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
感谢 R上。 Oosterholt 为抬头。
这篇关于Selenium,你如何检查滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!