我怎样才能写入原始数据?

问题描述 投票:0回答:2

我在测试一些东西,我一直得到错误 "write()参数必须是str,而不是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()

我可以得到原始数据,但我不能把它写入一个新的文件。有什么办法可以解决这个问题吗?

python python-requests web-crawler
2个回答
0
投票
  1. 当你在响应对象上调用.raw时,它返回一个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)
    

0
投票

试试这个方法

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' 以可写二进制模式打开文件。

© www.soinside.com 2019 - 2024. All rights reserved.