Scroll Element into View with Selenium

前端 未结 30 2659
时光说笑
时光说笑 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:02

    Selenium can scroll to some element in the scrollbar automatically for some simple UI, but for lazy-load UI, scrollToElement is still needed.

    This is my implementation in Java with JavascriptExecutor. You can find more details in Satix source code: http://www.binpress.com/app/satix-seleniumbased-automation-testing-in-xml/1958

    public static void perform(WebDriver driver, String Element, String ElementBy, By by) throws Exception {
     try {
      //long start_time = System.currentTimeMillis();           
      StringBuilder js = new StringBuilder();
      String browser = "firefox";
    
      if (ElementBy.equals("id")) {
       js.append("var b = document.getElementById(\"" +
        Element + "\");");
      } else if (ElementBy.equals("xpath")) {
       if (!"IE".equals(browser)) {
        js.append("var b = document.evaluate(\"" +
         Element +
         "\", document, null, XPathResult.ANY_TYPE, null).iterateNext();");
       } else {
        throw new Exception("Action error: xpath is not supported in scrollToElement Action in IE");
       }
      } else if (ElementBy.equals("cssSelector")) {
       js.append("var b = document.querySelector(\"" +
        Element + "\");");
      } else {
       throw new Exception("Scroll Action error");
      }
    
      String getScrollHeightScript = js.toString() + "var o = new Array(); o.push(b.scrollHeight); return o;";
    
      js.append("b.scrollTop = b.scrollTop + b.clientHeight;");
      js.append("var tmp = b.scrollTop + b.clientHeight;");
      js.append("var o = new Array(); o.push(tmp); return o;");
    
      int tries = 1;
      String scrollTop = "0";
      while (tries > 0) {
       try {
        String scrollHeight = ((JavascriptExecutor) driver).executeScript(getScrollHeightScript).toString();
        if (scrollTop.equals(scrollHeight)) {
         break;
        } else if (driver.findElement(by).isDisplayed()) {
         break;
        }
        Object o = ((JavascriptExecutor) driver).executeScript(js.toString());
        scrollTop = o.toString();
        Thread.sleep(interval);
        tries++;
       } catch (Exception e) {
        throw new Exception("Action error:" +
         " javascript execute error : " + e.getMessage() + ", javascript : " + js.toString());
       }
      }
    
     } catch (Exception e) {
      try {
       ScreenshotCapturerUtil.saveScreenShot(driver, CLASSNAME);
      } catch (IOException e1) {
       throw new Exception("Save screenshot error!", e1);
      }
      throw e;
     }
    }
    

提交回复
热议问题