You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium 4的CDP Page.printToPDF导出大页面PDF时触发TimeoutException的问题求助

Selenium 4的CDP Page.printToPDF导出大页面PDF时触发TimeoutException的问题求助

大家好,我最近在做一个用Selenium 4结合Chrome DevTools Protocol(CDP)导出页面为PDF的功能,遇到了一个棘手的问题:小页面导出完全正常,但页面内容变大后,调用Page.printToPDF方法会很快触发TimeoutException,根本没等到我设置的等待时间。

问题具体情况

我在调用driver.get(url)之后,特意用Thread.sleep(60000)让页面渲染1分钟,确保内容加载完成。但执行devTools.send(Page.printToPDF(...))的时候,短短几秒就抛出了超时异常,完全没达到我预期的等待时长。抛出的异常信息如下:

java.util.concurrent.TimeoutException
Build info: version: '4.18.1', revision: 'b1d3319b48'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.0-143-generic', java.version: '17.0.2'
Driver info: driver.version: unknown

我的环境信息

  • Selenium版本:4.18.1
  • Java版本:17.0.2
  • 操作系统:Ubuntu 22.04
  • ChromeDriver:无头模式(--headless=new),使用与CDP兼容的Chrome版本

完整代码片段

System.setProperty("webdriver.chrome.driver", "/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
options.addArguments("--window-size=1920,1080");
options.addArguments("--no-sandbox");
options.addArguments("--log-level=2");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--disable-gpu");
options.addArguments("--disable-software-rasterizer");

File downloadDir = new File(reportDir.getAbsolutePath() + File.separator + PDF);
if (!downloadDir.exists()) {
    downloadDir.mkdirs();
}

HashMap<String, Object> chromePrefs = new HashMap<>();
chromePrefs.put("profile.default_content_settings.popups", 0);
options.setExperimentalOption("prefs", chromePrefs);

// Ignore SSL certificate errors
options.addArguments("--ignore-certificate-errors");
options.addArguments("--allow-insecure-localhost");

ChromeDriver driver = null;
String url = "https://localhost:443/stat-report-pdf";
try {
    driver = new ChromeDriver(options);
    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.MINUTES);
    
    DevTools devTools = driver.getDevTools();
    devTools.createSession();
    
    driver.get(url);
    try {
        Thread.sleep(1 * 60 * 1000);
    } catch (InterruptedException e) {
        log.error("processPdfFile InterruptedException 에러");
        Thread.currentThread().interrupt();
    }
    
    Page.PrintToPDFResponse pdfResponse = devTools.send(
        Page.printToPDF(Optional.empty(), Optional.empty(), Optional.empty(), 
                        Optional.of(1), Optional.of(8.27), Optional.of(11.7), 
                        Optional.of(0.0), Optional.of(0.0), Optional.of(0.0), 
                        Optional.of(0.0), Optional.empty(), Optional.empty(), 
                        Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())
    );
    
    byte[] pdfData = Base64.getDecoder().decode(pdfResponse.getData());
    Path pdfPath = Paths.get(downloadDir.getAbsolutePath(), 
                            now.format(DateTimeFormatter.ofPattern("yyyyMMdd"))+"_MNX_Report.pdf");
    Files.write(pdfPath, pdfData);
    
    if( Files.exists(pdfPath) && Files.size(pdfPath) > 0) {
        log.debug("PDF file generate success: {}", pdfPath.toString());
        mailService.sendMailReport(pdfPath, startDate, endDate);
    } else {
        log.error("PDF file generate fail: {}", pdfPath.toString());
        return false;
    }
} catch (Exception e) {
    log.error("processPdfFile error = {}", e.getMessage());
    return false;
} finally {
    if (driver != null) {
        driver.quit();
    }
}
return true;

有没有大佬能帮忙分析下问题根源,或者给出可行的解决办法?非常感谢!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 12:49:35