2012-09-18 20 views
8

インターネット(イントラネット)リソースのコンテンツタイプをローカルファイルではなく取得する必要があります。どのように私は、URLの後ろにリソースからMIMEタイプを取得することができます。Python:URLのコンテンツタイプを取得するには?

私はこの試みた:私が手

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

を:私はContent-Typeを得ることができ、urllibを使用して行うことができますどのように ['charset=UTF-8']

をどのように、あるいはそうでない場合は、他の方法ですか?

+4

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

+0

印刷res.infoを参照してください。 ().gettype() –

+0

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

答えて

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

注:これはPython 2.xでのみ動作します –

10

Aこれまでの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 
関連する問題