2012-09-18 11 views
8

Tôi cần lấy loại nội dung của tài nguyên internet (mạng nội bộ) không phải là tệp cục bộ. Làm thế nào tôi có thể nhận được các loại MIME từ một nguồn lực đằng sau một URL:Python: Cách lấy Content-Type của URL?

Tôi cố gắng này:

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

tôi nhận được: ['charset=UTF-8']

Làm thế nào tôi có thể nhận được Content-Type, có thể được thực hiện bằng urllib và làm thế nào hoặc nếu không phải là cách khác là gì?

+4

Xem http://stackoverflow.com/questions/843392/python-get-http-headers-from-urllib-call – sqrtsben

+0

in res.info() .gettype() –

+0

http://stackoverflow.com/a/21515813/538284 –

Trả lời

15
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' 
+2

Lưu ý: công trình này chỉ dành cho python 2.x –

10

Một Python3 giải pháp này:

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