我怎样才能写原始数据?

How can i write raw data?

我正在测试一些东西,但我一直收到错误 "write() argument must be str, not HTTPResponse" 这是我的代码:

import requests
image="http://www.casperdenhaan.nl/wp-content/uploads/2020/03/Logo.jpg"
savefile=open("image.png","w+")
savefile.write(requests.get(image).raw)
savefile.close()

我可以获取原始数据,但无法将其写入新文件。有什么办法可以解决这个问题吗?

  1. 当您在响应对象上调用 .raw 时,它 returns 一个 HTTPResponse 对象。您需要调用 .content 来获取字节对象。

    type(requests.get(image).raw)
    urllib3.response.HTTPResponse
    
    type(requests.get(image).content)
    bytes
    
  2. 您需要以写入二进制模式打开文件:

    open("image.png","wb")
    
  3. 我建议使用 "with" 块,这样您就不需要明确关闭文件。这是代码的工作版本:

    import requests
    url = "http://www.casperdenhaan.nl/wp-content/uploads/2020/03/Logo.jpg"
    with open('image.png', 'wb') as f:
        f.write(requests.get(url).content)
    

试试这个方法

import requests
img_url = "http://www.casperdenhaan.nl/wp-content/uploads/2020/03/Logo.jpg"
img = requests.get(img_url)
with open('image.png', 'wb') as save_file:

        save_file.write(img.raw)

这样您就不必处理关闭文件的问题。此外,'wb' 以可写二进制模式打开文件。