From 660871f873d5a8c7a73122958417dc04bc1af441 Mon Sep 17 00:00:00 2001 From: guocan Date: Thu, 19 Jun 2025 18:04:31 +0800 Subject: [PATCH] =?UTF-8?q?fix=20=E4=BF=AE=E6=94=B9=E6=88=AA=E5=9B=BE?= =?UTF-8?q?=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/test/common/utils/SeleniumUtils.java | 59 +++++++++++++------ 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/test-common/src/main/java/com/test/common/utils/SeleniumUtils.java b/test-common/src/main/java/com/test/common/utils/SeleniumUtils.java index efccbc4..991c585 100644 --- a/test-common/src/main/java/com/test/common/utils/SeleniumUtils.java +++ b/test-common/src/main/java/com/test/common/utils/SeleniumUtils.java @@ -9,8 +9,9 @@ import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.File; -import java.io.IOException; +import java.text.SimpleDateFormat; import java.time.Duration; +import java.util.Date; import java.util.List; import java.util.Set; @@ -371,33 +372,53 @@ public class SeleniumUtils { return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); } + /** + * 截屏并保存为文件 + * @param filePath 保存路径的基础目录 + * @return 保存后的文件完整路径 + */ public String takeScreenshotAsFile(String filePath) { - // 获取截图文件 - File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); - try { - // 创建目标文件 - File destFile = new File(filePath); + // 生成文件名: screenshot_年月日_时分秒.png + String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); + String fileName = "screenshot_" + timestamp + ".png"; - // 确保父目录存在 - File parentDir = destFile.getParentFile(); - if (parentDir != null) { - parentDir.mkdirs(); + // 确保目录存在 + File directory = new File(filePath); + if (!directory.exists()) { + boolean created = directory.mkdirs(); + if (!created) { + log.error("无法创建目录: {}", filePath); + return null; + } } - // 将截图文件复制到指定路径 - FileUtils.copyFile(srcFile, destFile); + // 检查目录是否可写 + if (!directory.canWrite()) { + log.error("目录不可写: {}", filePath); + return null; + } - // 返回保存的文件路径 - return destFile.getAbsolutePath(); - } catch (IOException e) { - throw new RuntimeException("Failed to save screenshot to " + filePath, e); - } finally { - // 删除临时文件 - srcFile.delete(); + // 获取截图临时文件 + File tempFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + + // 构建目标文件路径 + String fullPath = filePath + File.separator + fileName; + File targetFile = new File(fullPath); + + // 复制文件到目标路径 + FileUtils.copyFile(tempFile, targetFile); + + log.info("截图已保存到: {}", targetFile.getAbsolutePath()); + return targetFile.getAbsolutePath(); + + } catch (Exception e) { + log.error("截图保存失败: {}", e.getMessage()); + return null; } } + // 关闭浏览器 public void quit() { if (driver != null) {