Scroll Element into View with Selenium

前端 未结 30 2690
时光说笑
时光说笑 2020-11-22 08:31

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 m

30条回答
  •  一个人的身影
    2020-11-22 09:13

    The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.

    Here is my solution for Java:

    public List getBoundedRectangleOfElement(WebElement we)
    {
        JavascriptExecutor je = (JavascriptExecutor) driver;
        List bounds = (ArrayList) 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;
    }
    

    And then, to scroll, you call it like this:

    public void scrollToElementAndCenterVertically(WebElement we)
    {
        List 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);
    }
    

提交回复
热议问题