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

如何用Python通过HTTP GET请求正确保存xlsm、docx、png、jpg文件

解决Python GET请求下载部分文件类型失败的问题

你的代码通过严格匹配完整的Content-Type字符串判断文件类型,但实际服务器返回的Content-Type可能存在格式差异(比如分号后带空格,如image/jpg; charset=UTF-8,而你代码中写的是image/jpg;charset=UTF-8),导致jpg、png、xlsm、docx对应的分支未触发,最终无法保存文件。

以下是针对性的优化方案:

方案1:忽略Content-Type的格式差异,简化类型判断

提取Content-Type的核心MIME类型(去掉charset等参数),用映射字典替代冗长的elif分支,同时用with语句自动管理文件操作,避免漏关文件:

import os

# 确保下载目录存在
os.makedirs('downloads', exist_ok=True)

# 处理Content-Type,提取核心MIME类型
base_content_type = contentType1.split(';')[0].strip()

# 建立MIME类型与文件后缀的映射
mime_ext_map = {
    'application/pdf': '.pdf',
    'image/jpeg': '.jpeg',
    'image/jpg': '.jpg',
    'image/png': '.png',
    'image/tiff': '.tiff',
    'image/jfif': '.jfif',
    'application/vnd.ms-excel': '.xls',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
    'application/vnd.ms-excel.sheet.macroEnabled.12': '.xlsm',
    'text/csv': '.csv'
}

# 根据映射保存文件
if base_content_type in mime_ext_map:
    file_ext = mime_ext_map[base_content_type]
    file_path = f'downloads/POD_{str(el)}{file_ext}'
    with open(file_path, 'wb') as pod_file:
        pod_file.write(response1.content)

方案2:直接从响应头获取文件名(如果服务器支持)

部分服务器会在Content-Disposition头中返回原始文件名,用这种方式更准确,无需手动匹配类型:

import os
import re

os.makedirs('downloads', exist_ok=True)

# 解析Content-Disposition头提取文件名
disposition_header = response1.headers.get('Content-Disposition')
if disposition_header:
    filename_match = re.search(r'filename="?([^"]+)"?', disposition_header)
    if filename_match:
        original_filename = filename_match.group(1)
        file_path = f'downloads/POD_{str(el)}_{original_filename}'
        with open(file_path, 'wb') as pod_file:
            pod_file.write(response1.content)

额外检查项

  • 确认响应状态码为200,避免下载错误页面(如404、500)的内容。
  • 若下载大文件,可改用response1.iter_content(chunk_size=1024)分块写入,避免内存占用过高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:45:30