1 #! /usr/local/bin/python -O
5 Written by BroytMann, Jun 2002 - Aug 2002. Copyright (C) 1997-2002 PhiloSoft Design
10 current_charset = sys.getdefaultencoding()
11 DEFAULT_CHARSET = "windows-1251"
14 from HTMLParser import HTMLParseError
15 from m_lib.www.html import HTMLParser as _HTMLParser
18 class HTMLHeadDone(Exception): pass
21 class HTMLParser(_HTMLParser):
22 def __init__(self, charset=None):
23 _HTMLParser.__init__(self)
24 self.charset = charset
33 def do_meta(self, attrs):
37 for attrname, value in attrs:
40 if attrname == 'http-equiv':
41 http_equiv = value.lower()
42 elif attrname == 'content':
45 if (not self.charset) and (http_equiv == "content-type"):
47 # extract charset from "text/html; foo; charset=UTF-8; bar;"
48 self.charset = content.lower().split('charset=')[1].split(';')[0]
53 if http_equiv == "refresh":
54 self.refresh = content
57 def start_title(self, attrs):
60 if not self.title: # use only the first title
61 self.title = self.accumulator
64 def parse_html(filename, charset=None, log=None):
65 infile = open(filename, 'r')
66 parser = HTMLParser(charset)
71 except (HTMLParseError, HTMLHeadDone):
78 except (HTMLParseError, HTMLHeadDone):
81 if not parser.charset:
85 if not (32 <= ord(c) <= 127): # non-ASCII character
89 parser.charset = DEFAULT_CHARSET
90 if parser.charset and (parser.charset <> current_charset):
92 if parser.meta_charset:
93 if log: log(" META charset : %s" % parser.charset)
95 if log: log(" charset : %s" % parser.charset)
96 if log: log(" title : %s" % parser.title)
97 parser.title = unicode(parser.title, parser.charset, "replace").encode(current_charset, "replace")
98 if log: log(" current charset: %s" % current_charset)
99 if log: log(" converted title: %s" % parser.title)
101 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
106 if __name__ == '__main__':
108 parser = parse_html(sys.argv[1])