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

点击链接后Puppeteer未实际下载ZIP文件的问题求助

问题解决指南

一、Puppeteer下载无文件的排查与修复

针对点击下载链接后无文件生成的问题,可从以下几个方向调整:

1. 确保下载目录的权限与存在性

你设置的路径/home/ubuntu/AirlineStatsFetcher/downloads需要满足两个前提:

  • 目录已存在:可在代码开头添加自动创建逻辑:
    const fs = require('fs');
    const dir = "/home/ubuntu/AirlineStatsFetcher/downloads";
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    
  • Node进程拥有该目录的读写权限:可通过终端命令调整:
    sudo chown -R ubuntu:ubuntu /home/ubuntu/AirlineStatsFetcher/downloads
    

2. 切换为新版无头模式

旧版headless: true对下载功能支持有限,建议替换为Puppeteer官方推荐的新版无头模式:

const browser = await puppeteer.launch({
  headless: "new", // 替换原headless: true
  slowMo: 100,
  executablePath: executablePath()
});

3. 添加下载事件监听与完成等待

点击链接后需监听下载流程,避免脚本提前结束导致文件未保存:

const path = require('path');

// 点击前注册下载监听
page.on('download', async (download) => {
  const filename = download.suggestedFilename();
  await download.saveAs(path.join(dir, filename));
  console.log(`文件已保存:${path.join(dir, filename)}`);
});

// 改用XPath匹配链接文本,提升选择器稳定性
const downloadLink = await page.waitForXPath('//a[text()="Download Raw Data"]');
await downloadLink.click();

// 可选:等待目录中出现文件后再继续执行
await page.waitForFunction((targetDir) => {
  return fs.readdirSync(targetDir).length > 0;
}, {}, dir);

4. 优化选择器可靠性

原CSS选择器依赖DOM层级结构,易因页面更新失效,改用XPath匹配链接文本的方式更稳定。

二、GET请求UNABLE_TO_VERIFY_LEAF_SIGNATURE错误处理

该错误源于服务器SSL证书链不完整,可临时通过以下方式解决(仅建议测试环境使用,生产环境需补充信任根证书):

  • 使用axios请求时添加配置:
    const axios = require('axios');
    const https = require('https');
    
    axios.get('你的完整下载URL', {
      httpsAgent: new https.Agent({ rejectUnauthorized: false })
    });
    
  • 使用fetch时配置Agent:
    const https = require('https');
    
    fetch('你的完整下载URL', {
      agent: new https.Agent({ rejectUnauthorized: false })
    });
    

内容的提问来源于stack exchange,提问作者ObjectNameDisplay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:50:37