fix: 修复导出下载 — 使用 waitForDownload 并输出绝对路径

- 用 page.waitForDownload 替代 onDownload + sleep,正确捕获下载事件
- 增加 5 分钟超时,等待服务器生成大文件
- 输出文件绝对路径和大小,不再找不到下载文件
- 只触发一次下载,不再重复

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Niko 2026-05-05 15:06:13 +08:00
parent 68d0cca25a
commit ea0f566e12

View File

@ -142,33 +142,31 @@ public class EtsScraper {
screenshot(page, "after_query");
// 点击导出按钮
boolean exportBtnExists = page.locator("#Export_ThreeBillList_Button").count() > 0;
if (exportBtnExists) {
// 点击导出按钮先弹出导出选项对话框再点击对话框内的导出
if (page.locator("#Export_ThreeBillList_Button").count() > 0) {
System.out.println("[*] Clicking export button...");
Download[] downloadHolder = new Download[1];
page.onDownload((java.util.function.Consumer<Download>) download -> {
downloadHolder[0] = download;
});
page.locator("#Export_ThreeBillList_Button").first().click();
if (downloadHolder[0] != null) {
System.out.println("[*] Waiting for download to complete...");
Download dl = downloadHolder[0];
Path downloadPath = Path.of("downloads");
// 设置下载目录
Path downloadPath = Path.of("downloads").toAbsolutePath().normalize();
java.nio.file.Files.createDirectories(downloadPath);
// 点击主导出按钮打开对话框再用 JS click 触发对话框内导出按钮
Download dl = page.waitForDownload(
new Page.WaitForDownloadOptions().setTimeout(300000),
() -> {
page.locator("#Export_ThreeBillList_Button").first().click();
sleep(2000);
System.out.println("[*] Triggering dialog export via JS...");
page.evaluate("document.querySelectorAll('button').forEach(b => { if (b.textContent.trim() === '导出') b.click(); })");
});
System.out.println("[*] Waiting for download to complete...");
Path savedFile = downloadPath.resolve(dl.suggestedFilename());
dl.saveAs(savedFile);
System.out.println("[+] Downloaded to: " + savedFile);
System.out.println("[+] Download saved to: " + savedFile);
if (java.nio.file.Files.size(savedFile) == 0) {
System.out.println("[-] Downloaded file is empty");
} else {
System.out.println("[+] Download size: " + java.nio.file.Files.size(savedFile) + " bytes");
}
}
} else {
System.out.println("[!] Export button not found");
}
screenshot(page, "after_export");
System.out.println("[+] Query and export completed!");