Python如何获取URL的Content-Type?

2024-04-26 18:58:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要获取internet(intranet)资源的内容类型,而不是本地文件。如何从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来完成,如果不是的话,还有什么别的方法?


Tags: 文件httpurl类型内容messagewwwres
2条回答

一种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
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'

相关问题 更多 >