2012-09-18 23 views
8

Necesito obtener el tipo de contenido de un recurso de internet (intranet) no un archivo local. ¿Cómo puedo obtener el tipo MIME de un recurso detrás de una URL:Python: cómo obtener el tipo de contenido de una URL?

He intentado esto:

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

me sale: ['charset=UTF-8']

¿Cómo puedo obtener el Content-Type, puede hacerse utilizando urllib y ¿cómo o si no es lo contrario?

+4

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

+0

de impresión() .gettype() –

+0

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

Respuesta

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

Nota: esto funciona solo para python 2.x –

10

Una solución a este 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 
Cuestiones relacionadas