Selenium验证div有一个滚动条

时间:2018-01-31 15:02:56

标签: javascript java selenium

我正在尝试验证特定div是否有滚动条,如何使用Selenium? 元素:

<div class="checkout-mini-cart">

代码:

JavascriptExecutor jsExecutor = (JavascriptExecutor)webDriver;
String script = "var div = document.getElementsByClassName('.checkout-mini-cart');" +
                "return div.scrollHeight < div.clientHeight;";
Object isScrollable = jsExecutor.executeScript(script);

它总是返回false,因为“return div.scrollHeight;”返回null。如何以正确的方式做到这一点?

1 个答案:

答案 0 :(得分:4)

代码document.getElementsByClassName返回一个数组而不是DOM元素。

使用脚本注入检查元素是否可滚动:

String JS_ELEMENT_IS_SCROLLABLE = 
    "return arguments[0].scrollHeight > arguments[0].offsetHeight;";

JavascriptExecutor jse = (JavascriptExecutor)webDriver;

WebElement container = driver.findElement(By.cssSelector(".checkout-mini-cart"));
Boolean isScrollable = (Boolean)jse.executeScript(JS_ELEMENT_IS_SCROLLABLE, container);

或阅读属性:

WebElement container = driver.findElement(By.cssSelector(".checkout-mini-cart"));
int scrollHeight = parseInt(container.getAttribute("scrollHeight"));
int offsetHeight = parseInt(container.getAttribute("offsetHeight"));
Boolean isScrollable = scrollHeight> offsetHeight;