【问题标题】:How can i write raw data?我怎样才能写原始数据?
【发布时间】:2020-06-03 20:27:19
【问题描述】:

我正在测试一些东西,但我不断收到错误“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()

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

【问题讨论】:

  • 我该怎么做?
  • savefile.write(requests.get(image).content)
  • 是的,这行得通!我试过了,你都需要。

标签: python python-requests web-crawler


【解决方案1】:
  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)
    

【讨论】:

    【解决方案2】:

    试试这个方法

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

    【讨论】:

      猜你喜欢
      • 2012-08-20
      • 2021-12-16
      • 2014-04-05
      • 2021-03-17
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      相关资源
      最近更新 更多