2012-09-18 23 views
8

मुझे सामग्री-प्रकार इंटरनेट (इंट्रानेट) संसाधन को स्थानीय फ़ाइल नहीं प्राप्त करने की आवश्यकता है। urllib का उपयोग कर ['charset=UTF-8']पायथन: यूआरएल की सामग्री-प्रकार कैसे प्राप्त करें?

मैं Content-Type कैसे प्राप्त कर सकते हैं, किया जा सकता है:

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

मैं हो: मैं इस कोशिश की

: मैं कैसे एक यूआरएल के पीछे एक संसाधन से MIME प्रकार प्राप्त कर सकते हैं और कैसे या नहीं, दूसरी तरफ क्या है?

+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

नोट: यह केवल पायथन 2.x के लिए काम करता है –

10

एक 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