Welcome, guest | Sign In | My Account | Store | Cart

Determine if a particular URL is of a particular type (i.e., "text" for HTML, "image" for gif). It supports either the URL in string form, or an open file (obtained from urllib.urlopen).

Python, 29 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import urllib
from types import *
def iscontenttype(URLorFile,contentType='text'):
    """
    Return true or false (1 or 0) based on HTTP Content-Type.
    Accepts either a url (string) or a "urllib.urlopen" file.
    
    Defaults to 'text' type.
    Only looks at start of content-type, so you can be as vague or precise
    as you want.
    For example, 'image' will match 'image/gif' or 'image/jpg'.
    """
    result = 1
    try:
        if type(URLorFile) == StringType:
            file=urllib.urlopen(URLorFile)
        else:
            file = URLorFile

        testType=file.info().getheader("Content-Type")
        if testType and testType.find(contentType) == 0:
            result=1
        else:
            result=0
        if type(URLorFile) == StringType:
            file.close()
        return result
    except:
        return 0