5 Written by BroytMann. Copyright (C) 1997-2005 PhiloSoft Design
10 current_charset = sys.getdefaultencoding()
11 if current_charset == "ascii":
17 current_charset = locale.getpreferredencoding()
18 current_charset = current_charset.replace("windows-", "cp").lower()
19 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
22 from HTMLParser import HTMLParseError
23 from m_lib.net.www.html import HTMLParser as _HTMLParser
26 class HTMLHeadDone(Exception): pass
29 class HTMLParser(_HTMLParser):
30 def __init__(self, charset=None):
31 _HTMLParser.__init__(self)
32 self.charset = charset
41 def do_meta(self, attrs):
45 for attrname, value in attrs:
48 if attrname == 'http-equiv':
49 http_equiv = value.lower()
50 elif attrname == 'content':
53 if (not self.charset) and (http_equiv == "content-type"):
55 # extract charset from "text/html; foo; charset=UTF-8; bar;"
56 self.charset = content.lower().split('charset=')[1].split(';')[0]
57 self.meta_charset = 1 # Remember that the charset was retrieved from
58 # META tag, not from the Content-Type header
62 if http_equiv == "refresh":
63 self.refresh = content
66 def start_title(self, attrs):
70 if not self.title: # use only the first title
71 self.title = self.accumulator
75 entity_re = re.compile("(&#[0-9]+;)")
77 def recode_entities(title, charset):
79 for part in entity_re.split(title):
80 if entity_re.match(part):
81 part = unichr(int(part[2:-1])).encode(charset, "replace")
84 return ''.join(output)
87 def parse_html(filename, charset=None, log=None):
88 infile = open(filename, 'r')
89 parser = HTMLParser(charset)
94 except (HTMLParseError, HTMLHeadDone):
101 except (HTMLParseError, HTMLHeadDone):
106 if not parser.charset:
108 unicode(title, "ascii")
109 except UnicodeDecodeError:
110 parser.charset = DEFAULT_CHARSET
113 parser.charset = parser.charset.replace("windows-", "cp").lower()
115 if parser.charset and (parser.charset <> current_charset):
117 if parser.meta_charset:
118 if log: log(" META charset : %s" % parser.charset)
120 if log: log(" charset : %s" % parser.charset)
121 if log: log(" title : %s" % title)
122 title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
123 if log: log(" current charset: %s" % current_charset)
124 if log: log(" converted title: %s" % title)
126 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
128 parser.title = recode_entities(title, current_charset)
132 if __name__ == '__main__':
134 parser = parse_html(sys.argv[1])