fix 修改截图路径
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user