【问题标题】:Python header request wrong content type/Error 404Python 标头请求错误的内容类型/错误 404
【发布时间】:2021-12-08 22:37:02
【问题描述】:

我想通过检查标头请求的内容类型来找出文件格式。 我有一个 csv 文件的下载链接。如果我检查内容类型,它会显示 text/html,如果我尝试运行 status_code,则会收到错误 404。

如果我在终端中使用 curl -v 运行它,我会得到正确的内容类型。 有人知道如何在 python 中解决这个问题吗? 提前谢谢!

这是我到目前为止所做的:

import requests
url = "https://stats.oecd.org/sdmx-json/data/DP_LIVE/.GDP.../OECD?contentType=csv&detail=code&separator=comma&csv-lang=en"
    
r = requests.head(url)
headerDict=r.headers
print(headerDict)

我回来了:

{'Cache-Control': 'private', 'Content-Length': '4941', 'Content-Type': 'text/html; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'POST, GET,OPTIONS', 'Date': 'Fri, 22 Oct 2021 08:54:31 GMT', 'Connection': 'close'}

【问题讨论】:

    标签: python python-requests http-headers


    【解决方案1】:

    您可以使用它来获取内容类型

    import requests
    import mimetypes
    
    response = requests.get('https://stats.oecd.org/sdmx-json/data/DP_LIVE/.GDP.../OECD?contentType=csv&detail=code&separator=comma&csv-lang=en')
    content_type = response.headers['content-type']
    extension = mimetypes.guess_extension(content_type)
    print(content_type)
    print(extension)
    

    输出

    text/csv
    .csv
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 2012-06-01
      • 2022-07-20
      • 1970-01-01
      • 2013-01-29
      • 2020-11-15
      • 1970-01-01
      相关资源
      最近更新 更多