有没有办法在硒1。X或2。x来滚动浏览器窗口,以便XPath标识的特定元素在浏览器的视图中?在Selenium中有一个focus方法,但在FireFox中它似乎不能物理地滚动视图。有人有什么建议吗?

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


当前回答

我发现元素的边框不正确,导致浏览器滚动到屏幕外。然而,下面的代码对我来说工作得相当好:

private void scrollToElement(WebElement webElement) throws Exception {
    ((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
    Thread.sleep(500);
}

其他回答

Selenium 2尝试滚动到元素,然后单击它。这是因为除非Selenium 2认为元素是可见的,否则它不会与元素交互。

滚动到元素是隐式的,所以您只需要找到项目,然后使用它。

这招对我很管用:

IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
 ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);

对我有用的是使用浏览器。在浏览器窗口底部的元素上使用MoveMouseToElement方法。神奇的是,它在ie、Firefox和Chrome浏览器上都能正常运行。

我选择这种方法而不是JavaScript注入技术,只是因为它感觉不那么生硬。

Selenium的默认行为是滚动,因此元素几乎不在视口顶部的视图中。此外,并非所有浏览器都具有完全相同的行为。这很不令人满意。如果您像我一样记录浏览器测试的视频,那么您需要的是元素滚动到视图中并垂直居中。

下面是我的Java解决方案:

public List<String> getBoundedRectangleOfElement(WebElement we)
{
    JavascriptExecutor je = (JavascriptExecutor) driver;
    List<String> bounds = (ArrayList<String>) je.executeScript(
            "var rect = arguments[0].getBoundingClientRect();" +
                    "return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
    System.out.println("top: " + bounds.get(1));
    return bounds;
}

然后,为了滚动,你像这样调用它:

public void scrollToElementAndCenterVertically(WebElement we)
{
    List<String> bounds = getBoundedRectangleOfElement(we);
    Long totalInnerPageHeight = getViewPortHeight(driver);
    JavascriptExecutor je = (JavascriptExecutor) driver;
    je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
    je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}

我一直在用ADF组件做测试,如果使用惰性加载,你必须有一个单独的滚动命令。如果未加载对象,并且尝试使用Selenium查找它,则Selenium将抛出一个“元素未找到”异常。