2012-09-18 30 views
8

Bir internet (intranet) kaynağının içerik türünü yerel dosya olarak almam gerekir. Bir URL'ye arkasında bir kaynaktan MIME türü nasıl alabilirim: urllib kullanarak ['charset=UTF-8']Python: Bir URL'nin İçerik Türü nasıl edinilir?

nasıl Content-Type alabilirsiniz yapılabilir:

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

Ben olsun:

Bu çalıştı ve nasıl ya da değilse diğer yol nedir?

+4

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

+0

baskı res.info() .gettype() –

+0

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

cevap

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

Not: Bu yalnızca python 2.x için geçerlidir. –

10
Buna

A Python3 çözümü:

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 
İlgili konular