Python:如何获取 URL 的内容类型?

标签 python python-2.7 urllib

我需要获取互联网(内联网)资源的内容类型,而不是本地文件。如何从 URL 后面的资源获取 MIME 类型:

我试过这个:

res = urllib.urlopen("http://www.iana.org/assignments/language-subtag-registry")
http_message = res.info()
message = http_message.getplist()

我得到: ['charset=UTF-8']

我怎样才能得到 Content-Type,可以使用 urllib 来完成,如果不能,还有其他方法吗?

最佳答案

对此的 Python3 解决方案:

import urllib.request
with urllib.request.urlopen('http://www.google.com') as response:
    info = response.info()
    print(info.get_content_type())      # -> text/html
    print(info.get_content_maintype())  # -> text
    print(info.get_content_subtype())   # -> html

关于Python:如何获取 URL 的内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12474406/

相关文章:

python - 是否有 urllib.parse.quote 的幂等版本?

python - urllib.error.URLError : <urlopen error unknown url type: https>

python - 在 for 循环中使用 unpack 与在 python 中不使用 unpack 有什么区别

python - 在Python中使用OpenCv检测几乎直线

python - 获取反转列表的长度

python - 具有多处理卡住计算机的 Matplotlib

python - Pandas 遍历行并找到列名

python - 如何向 PyPi 分发类型提示?

python - 如何删除字符串中*在特定分隔符*内的特定字符*,例如括号内

python - 我正在尝试使用 python 请求创建用于网络抓取的 POST 数据