直接用 response.content 以 "wb" 模式写入 .xml 文件最稳妥,避免使用 response.text 导致编码错乱;大文件启用 stream=True 分块写入;保留原始字节,不 decode/encode,确保 lxml 等能正确解析。

requests.get() 返回的 content 怎么写入 .xml 文件
直接用 response.content 写二进制文件最稳妥,别用 response.text —— XML 常含 UTF-8 BOM、特殊字符或编码声明(如 <?xml version="1.0" encoding="GBK"?>),用 .text 会触发 requests 自动解码,可能破坏原始字节或引发编码错乱。
- 始终以
"wb"模式打开文件:open("output.xml", "wb") - 写入前不 decode,不 encode,不替换换行符,不 strip 空格
- 如果服务端返回
Content-Encoding: gzip,response.content已自动解压,无需额外处理
如何确保保存后的 XML 能被 lxml 或 xml.etree 正确解析
关键在三件事:保留原始响应头里的 Content-Type 编码信息、不引入 Windows CRLF 破坏格式、避免编辑器自动转码。requests 默认按 response.headers.get("content-type") 推断编码,但写文件时这个信息就丢了。
- 检查响应头:
print(response.headers.get("content-type")),留意是否有charset=参数(如application/xml; charset=GB2312) - 若需人工验证编码,用
chardet.detect(response.content)辅助判断,但不要用它结果去 decode 后再写 —— 写原始 bytes 才安全 - 保存后用命令行快速验:
file -i output.xml(Linux/macOS)或用 VS Code 以“UTF-8 with BOM”/“GBK”等编码重载查看是否乱码
遇到 UnicodeEncodeError 或中文变 怎么办
这几乎全是误用 response.text 导致的。requests 把 bytes 解成 str 时若没对上实际编码,就会出 ;再用默认系统编码(如 cp1252)写文件,问题叠加。
- 删掉所有
.text、.json()、.content.decode(...)相关逻辑 - 确认目标路径无中文或空格(尤其 Windows 下某些旧工具对路径编码敏感)
- 如果必须用
text(比如要日志打印片段),只用于调试,写文件仍走content
requests 下载大 XML 文件要不要流式处理
看大小。小于 10MB,直接 response.content 简单可靠;超过 50MB,建议用 stream=True + 分块写入,防内存爆掉,也方便加进度条或断点续传。
立即学习“Python免费学习笔记(深入)”;
- 启用流式:
response = requests.get(url, stream=True) - 检查状态码后再读:
response.raise_for_status()(否则iter_content可能抛异常) - 写入示例:
with open("large.xml", "wb") as f: for chunk in response.iter_content(chunk_size=8192): if chunk: f.write(chunk)
XMLSyntaxError: not well-formed (invalid token)。所以别碰 content,让它原样落盘。









