public class PaintScreenUilts {
private static final Logger LOGGER = LoggerFactory.getLogger(PaintScreenUilts.class);
private static int count = 0;
/**
* 网页截图
*
* @param webPathInfo 网页地址
*/
public static void webPrintScreen(WebPrintScreenInfo webPathInfo, List<String> filePathList) {
LOGGER.info("start print screen WebPrintScreenInfo {}", webPathInfo.toString());
try {
if (count <= 4) {
filePathList.clear();
printScreen(webPathInfo, filePathList);
} else {
return;
}
} catch (Exception e) {
count++;
LOGGER.error(" print screen error {}", e.getMessage());
// 截图有可能网速加载太慢导致截图失败,这里从新尝试截图5次。
webPrintScreen(webPathInfo, filePathList);
}
}
/**
* 网页截图开始
*
* @param webPathInfo 网页数据对象
* @throws Exception 异常
*/
public static void printScreen(WebPrintScreenInfo webPathInfo, List<String> filePathList) throws Exception {
Thread.sleep(5000);
WebDriver webDriver = null;
try {
System.setProperty("webdriver.chrome.driver", FilePathConstant.DRIVER_PATH);
ChromeOptions chromeOptions = new ChromeOptions();
// 截取网页全图这个设置很重要
chromeOptions.addArguments("-headless");
webDriver = new ChromeDriver(chromeOptions);
webDriver.manage().window().maximize();
webDriver.manage().deleteAllCookies();
// 与浏览器同步非常重要,必须等待浏览器加载完毕
webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//打开目标地址
webDriver.get(webPathInfo.getUrl());
if (webPathInfo.isLogin()) {
LOGGER.info(" print screen start login");
webDriver.findElement(By.id(FilePathConstant.USER_SELECTOR)).sendKeys(FilePathConstant.USER);
webDriver.findElement(By.id(FilePathConstant.PASSWORD_SELECTOR)).sendKeys(FilePathConstant.PASSWORD);
// 点击"登录"
webDriver.findElement(By.className(FilePathConstant.LOGIN_BTN)).click();
Thread.sleep(3000);
}
// 点击事件
Actions action = new Actions(webDriver);
if (StringUtils.isNotEmpty(webPathInfo.getClickEventXPath())) {
String[] ClickEventXPathSplit = webPathInfo.getClickEventXPath().split(";");
for (String ClickXpath : ClickEventXPathSplit) {
//切换按钮点击事件
LOGGER.info(" print screen start action event.");
action.click(webDriver.findElement(By.xpath(ClickXpath))).perform();
Thread.sleep(3000);
}
}
// 截取图片
if (StringUtils.isNotEmpty(webPathInfo.getWebPrintScreenXPath())) {
String[] webPrintScreenXPathSplit = webPathInfo.getWebPrintScreenXPath().split(";");
LOGGER.info(" print screen start event.");
for (String screenXpath : webPrintScreenXPathSplit) {
extracted(screenXpath, filePathList, webDriver);
}
} else {
//获取窗口高度 截网页全图
Object width = ((JavascriptExecutor) webDriver).executeScript("return document.body.scrollWidth");
Object height = ((JavascriptExecutor) webDriver).executeScript("return document.body.scrollHeight");
webDriver.manage().window().setSize(new Dimension(Integer.parseInt(String.valueOf(width)), Integer.parseInt(String.valueOf(height))));
webDriver.manage().window().fullscreen();
extracted(filePathList, webDriver);
}
} catch (Exception e) {
throw new Exception(e.getMessage());
} finally {
if (webDriver != null) {
webDriver.quit();
}
}
}
private static void extracted(List<String> filePathList, WebDriver webDriver) throws InterruptedException, IOException {
LOGGER.info("print full screen start.");
Date date = new Date();
String format = FilePathConstant.formatter.format(date);
String filePath = FilePathConstant.TEMP_FILE_PATH + "/" + format + ".png";
File imgPath = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
BufferedImage img = ImageIO.read(imgPath);
ImageIO.write(img, "png", imgPath);
FileUtils.copyFile(imgPath, new File(filePath));
filePathList.add(filePath);
}
/**
* 剪裁图片
*
* @param screenXpath 剪裁数据
* @param filePathList 文件路径
* @param webDriver 浏览器驱动
* @throws InterruptedException
* @throws IOException
*/
private static void extracted(String screenXpath, List<String> filePathList, WebDriver webDriver) throws InterruptedException, IOException {
//找图表
WebElement img = webDriver.findElement(By.xpath(screenXpath));
Thread.sleep(3000);
//获取窗口高度
Object o1 = ((JavascriptExecutor) webDriver).executeScript("return document.documentElement.clientHeight");
int windowsHeight = Integer.parseInt(String.valueOf(o1));
//图片位置
Point location = img.getLocation();
//图片y坐标
int y = location.getY();
//窗口滑动高度
int move = y + img.getSize().height > windowsHeight ? y + img.getSize().height - windowsHeight : 0;
//滑动窗口
if (move > 0) {
((JavascriptExecutor) webDriver).executeScript("window.scrollTo(0, " + move + ")");
}
Thread.sleep(3000);
File imgPath = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
Date date = new Date();
String format = FilePathConstant.formatter.format(date);
String filePath = FilePathConstant.TEMP_FILE_PATH + "/" + format + ".png";
FileUtils.copyFile(captureElement(imgPath, img, move), new File(filePath));
filePathList.add(filePath);
}
/**
* 剪截图片
*
* @param filePath 文件地址
* @param element 网页元素
* @param move 开始截取的差值
* @return 返回文件路径
* @throws IOException 异常
*/
public static File captureElement(File filePath, WebElement element, int move) throws IOException {
BufferedImage img = ImageIO.read(filePath);
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
Point point = element.getLocation();
//从元素左上角坐标开始,按照元素的高宽对img进行裁剪为符合需要的图片
BufferedImage dest = img.getSubimage(point.getX(), point.getY() - move, width, height);
ImageIO.write(dest, "png", filePath);
return filePath;
}
java+selenium 截取网页全图,部分图
最新推荐文章于 2024-01-17 10:13:43 发布