Selemium实现长截图

import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import org.openqa.selenium.*;
import org.openqa.selenium.Dimension;
public void changeWindows(String windowName) {
  try {
    Set<String> windowsSet = driver.getWindowHandles();
    for (String newHandle : windowsSet) {
      if (!newHandle.equals(windowName)) {
        driver.switchTo().window(newHandle);
        logger.info("Switch Window success From " + windowName + " to " + newHandle);
      }
    }
  } catch (Exception e) {
    logger.info("Handles switch  accept exception: {}", e.getMessage());
  }
}

public void longScreenShot(String screenShotFileName) {
   Screenshot screenshot =
           new AShot()
                   .shootingStrategy(ShootingStrategies.viewportPasting(1000))
                   .takeScreenshot(driver);
   try {
     ImageIO.write(screenshot.getImage(),"PNG",new File(TARGET_SCREENSHOTS_PATH + screenShotFileName + ".png"));
     logger.info("Long screenshot obtained successfully :long screen Shot file Name is {}",screenShotFileName);
   } catch (IOException e) {
     logger.error("Long screenshot obtained fail");
     e.printStackTrace();
   }
}

public void screenshot( String screenShotFileName) {
  if (Boolean.parseBoolean(GlobalVar.GLOBAL_VARIABLES.get("headless"))==true) {
    JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
    int maxWidth = Integer.parseInt(String.valueOf(javascriptExecutor.executeScript("return Math.max(document.body.scrollWidth,document.body.offsetWidth, document.documentElement.clientWidth, document.documentElement.scrollWidth, document.documentElement.offsetWidth);")));
    logger.info("获取网页最大宽度:" + maxWidth);
    int maxHeight = Integer.parseInt(String.valueOf(javascriptExecutor.executeScript("return Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);")));
    logger.info("获取网页最大高度:" + maxHeight);
    driver.manage().window().setSize(new Dimension(maxWidth, maxHeight));
    File srcfile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    try {
      FileUtils.copyFile(srcfile, new File(TARGET_SCREENSHOTS_PATH + screenShotFileName + ".png"));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  if (Boolean.parseBoolean(GlobalVar.GLOBAL_VARIABLES.get("headless"))==false){
    longScreenShot(screenShotFileName);
  }
}

猜你喜欢

转载自blog.csdn.net/qq_30273575/article/details/133015578