Python将二进制图像(PNG)数据写入文件

Python将二进制图像(PNG)数据写入文件,python,file-io,png,python-requests,Python,File Io,Png,Python Requests,我正在使用requests模块连接一个返回PNG图像的php脚本。如果我这样做: import requests r=requests.get("http://location/script.php", cookies=cookies) fp = open("image.png", "wb") fp.write(r.text) #r.text is the binary data for the PNG returned by that php script fp.close() 但是它在编写

我正在使用
requests
模块连接一个返回PNG图像的php脚本。如果我这样做:

import requests
r=requests.get("http://location/script.php", cookies=cookies)
fp = open("image.png", "wb")
fp.write(r.text) #r.text is the binary data for the PNG returned by that php script
fp.close()
但是它在编写时给出了一个UnicodeEncodeError,所以我使用了
fp.write(r.text.encode(“utf-8”)
而不是
fp.write(r.text)
。 该文件已创建,但我无法在图像查看器中查看它(它给出了一个错误)。但是,如果我右键单击并将该脚本返回的PNG保存在Firefox中,我可以在保存后在相同的图像查看器中查看它。所以我猜我将图像数据写入文件的方式有问题。
还有其他方法吗?

r.text
不是二进制数据。该属性为您提供解码文本,即Unicode值


您可能希望改用
r.content
,或者将图像流式传输到文件设置
stream=True
,并从
r.raw
文件对象进行复制

r.text
不是二进制数据。该属性为您提供解码文本,即Unicode值

您可能希望改用
r.content
,或者将图像流式传输到文件设置
stream=True
,并从
r.raw
文件对象进行复制