1 #! /usr/local/bin/python -O
5 Written by BroytMann, Jun 2002 - May 2003. Copyright (C) 1997-2003 PhiloSoft Design
10 current_charset = sys.getdefaultencoding()
11 DEFAULT_CHARSET = "windows-1251" # Stupid default for Russian Cyrillic
14 from HTMLParser import HTMLParseError
15 from m_lib.net.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]
49 self.meta_charset = 1 # Remember that the charset was retrieved from
50 # META tag, not from the Content-Type header
54 if http_equiv == "refresh":
55 self.refresh = content
58 def start_title(self, attrs):
62 if not self.title: # use only the first title
63 self.title = self.accumulator
67 entity_re = re.compile("(&#[0-9]+;)")
69 def recode_entities(title, charset):
71 for part in entity_re.split(title):
72 if entity_re.match(part):
73 part = unichr(int(part[2:-1])).encode(charset, "replace")
76 return ''.join(output)
79 def parse_html(filename, charset=None, log=None):
80 infile = open(filename, 'r')
81 parser = HTMLParser(charset)
86 except (HTMLParseError, HTMLHeadDone):
93 except (HTMLParseError, HTMLHeadDone):
98 if not parser.charset:
101 if not (32 <= ord(c) <= 127): # non-ASCII character
105 parser.charset = DEFAULT_CHARSET
107 if parser.charset and (parser.charset <> current_charset):
109 if parser.meta_charset:
110 if log: log(" META charset : %s" % parser.charset)
112 if log: log(" charset : %s" % parser.charset)
113 if log: log(" title : %s" % title)
114 title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
115 if log: log(" current charset: %s" % current_charset)
116 if log: log(" converted title: %s" % title)
118 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
120 parser.title = recode_entities(title, current_charset)
124 if __name__ == '__main__':
126 parser = parse_html(sys.argv[1])