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

Python Requests意外解码application/x-gzip内容问题求助

解决requests获取gzip文件却得到解压后CSV的问题

嘿,我懂你遇到的这个小困扰!其实这完全是requests库的默认“贴心”行为导致的——它会自动帮你解压gzip压缩的响应内容。

为什么会这样?

requests发送请求时,默认会在请求头里带上Accept-Encoding: gzip, deflate,相当于告诉服务器:“我能处理压缩后的内容,尽管发过来!”。当服务器返回gzip格式的文件后,requests会自动完成解压操作,所以你拿到的resp.content已经是解压后的CSV数据,而不是你预期的原始.gz压缩文件。

两种解决方法

如果你想要获取原始的gzip压缩文件,可以试试下面两种方式:

方法一:修改请求头,不接受gzip编码

直接在请求里设置Accept-Encoding为identity,告诉服务器不要返回压缩内容:

url = 'https://donneespubliques.meteofrance.fr/donnees_libres/Txt/Synop/Archive/synop.201803.csv.gz'
headers = {'Accept-Encoding': 'identity'}
resp = requests.get(url, headers=headers)

# 保存原始gzip文件
with open('synop.201803.csv.gz', 'wb') as f:
    f.write(resp.content)

方法二:使用stream模式禁用自动解压

开启stream=True,然后修改resp.raw的decode_content属性为False,阻止自动解压:

url = 'https://donneespubliques.meteofrance.fr/donnees_libres/Txt/Synop/Archive/synop.201803.csv.gz'
resp = requests.get(url, stream=True)
resp.raw.decode_content = False  # 关闭自动解压

# 读取并保存原始压缩数据
with open('synop.201803.csv.gz', 'wb') as f:
    f.write(resp.raw.read())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:58:47