Skip to main content
 首页 » 编程设计

Python请求unicode错误

2025年05月04日15kerrycode

我正在使用一个简单的 Python 脚本将文件发布到 PHP 脚本:

... 
url = "http://example.com/upload.php" 
r = requests.post(url, data=data, files=files) 
... 

我需要捕获存储在中的响应文本

r.text 

但是当响应包含 ASCII 字符(例如图像文件)时,Python 会失败并出现此错误:

content = str(self.content, encoding, errors='replace') 
TypeError: unicode() argument 2 must be string, not None 

有什么办法可以避免这个错误吗?

请您参考如下方法:

图像等二进制文件没有相关的字符编码。使用 r.content 而不是 r.text。