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

PHP服务器PDF批量下载优化:避免生成空文件

优化后的PDF/Word下载代码

核心优化点

  • 复用requests.Session()减少连接开销
  • 增加文件存在性判断,避免生成空文件
  • 自动识别文件类型(PDF/Word),匹配正确后缀名
  • 不存在文件时输出提示信息

完整代码

import requests

# 初始化Session,复用连接提升效率
session = requests.Session()
save_base_path = "/Users/aartimalik/Downloads/test/"

# 生成目标编号的URL列表,无需手动逐个编写
start_id = 13980
end_id = 14000
urls = [(str(num), f"http://ppmoe.dot.ca.gov/des/oe/awards/bidsum/dl.php?id={num}") for num in range(start_id, end_id + 1)]

for number, url in urls:
    try:
        response = session.get(url, timeout=10)
        response.raise_for_status()  # 捕获4xx/5xx等HTTP错误状态码
        
        # 判断内容有效性:排除空内容或非文档类型响应
        if len(response.content) == 0:
            print(f"ID {number}: no pdf/word file")
            continue
        
        # 根据响应头识别文件类型,匹配对应后缀
        content_type = response.headers.get('Content-Type', '')
        if 'application/pdf' in content_type:
            file_ext = '.pdf'
        elif 'application/msword' in content_type:
            file_ext = '.doc'
        elif 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' in content_type:
            file_ext = '.docx'
        else:
            print(f"ID {number}: no pdf/word file")
            continue
        
        # 仅当文件有效时才写入
        full_file_path = f"{save_base_path}{number}_phptest{file_ext}"
        with open(full_file_path, "wb") as f:
            f.write(response.content)
        print(f"ID {number}: 已保存 {full_file_path}")
    
    except requests.exceptions.RequestException as e:
        print(f"ID {number}: 请求失败 - {str(e)}")

关键逻辑说明

  1. Session复用:将requests.Session()放在循环外部,避免每次请求新建连接,大幅提升批量下载效率。
  2. 有效性判断:
    • 检查响应内容长度,为空则直接判定文件不存在
    • 通过Content-Type响应头过滤非PDF/Word类型的内容
    • 用response.raise_for_status()捕获HTTP错误,比如404、500等
  3. 自动后缀处理:根据服务器返回的文件类型自动选择对应后缀,避免错误保存为PDF格式。
  4. 异常防护:捕获超时、连接失败等异常,保证批量下载时程序不会中途崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:31:03