Python:如何获取URL的Content-Type?

Edu*_*scu 11 python urllib python-2.7

我需要获取Internet(Intranet)资源的内容类型而不是本地文件.如何从URL后面的资源获取MIME类型:

我试过这个:

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

我明白了: ['charset=UTF-8']

我怎样才能获得Content-Type,可以使用urllib以及如何以及如果不是这样的方式?

Mik*_*kin 18

res = urllib.urlopen("http://www.iana.org/assignments/language-subtag-registry" )
http_message = res.info()
full = http_message.type # 'text/plain'
main = http_message.maintype # 'text'
Run Code Online (Sandbox Code Playgroud)

  • 注意:这仅适用于python 2.x. (5认同)

Dom*_*Cat 16

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
Run Code Online (Sandbox Code Playgroud)