5 Written by BroytMann. Copyright (C) 1997-2007 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
42 def do_meta(self, attrs):
46 for attrname, value in attrs:
49 if attrname == 'http-equiv':
50 http_equiv = value.lower()
51 elif attrname == 'content':
54 if (not self.charset) and (http_equiv == "content-type"):
56 # extract charset from "text/html; foo; charset=UTF-8; bar;"
57 self.charset = content.lower().split('charset=')[1].split(';')[0]
58 self.meta_charset = 1 # Remember that the charset was retrieved from
59 # META tag, not from the Content-Type header
63 if http_equiv == "refresh":
64 self.refresh = content
67 def start_title(self, attrs):
71 if not self.title: # use only the first title
72 self.title = self.accumulator
75 def do_link(self, attrs):
79 for attrname, value in attrs:
81 value = value.strip().lower()
82 if (attrname == 'rel') and (value in ('icon', 'shortcut icon')):
84 elif attrname == 'href':
94 entity_re = re.compile("(&#[0-9]+;)")
96 def recode_entities(title, charset):
98 for part in entity_re.split(title):
99 if entity_re.match(part):
100 part = unichr(int(part[2:-1])).encode(charset, "replace")
103 return ''.join(output)
106 def parse_html(filename, charset=None, log=None):
107 infile = open(filename, 'r')
108 parser = HTMLParser(charset)
113 except (HTMLParseError, HTMLHeadDone):
120 except (HTMLParseError, HTMLHeadDone):
125 if not parser.charset:
127 unicode(title, "ascii")
128 except UnicodeDecodeError:
129 parser.charset = DEFAULT_CHARSET
132 parser.charset = parser.charset.replace("windows-", "cp").lower()
134 if parser.charset and (parser.charset <> current_charset):
136 if parser.meta_charset:
137 if log: log(" META charset : %s" % parser.charset)
139 if log: log(" charset : %s" % parser.charset)
140 if log: log(" title : %s" % title)
141 title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
142 if log: log(" current charset: %s" % current_charset)
143 if log: log(" converted title: %s" % title)
145 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
147 parser.title = recode_entities(title, current_charset)
151 if __name__ == '__main__':
153 parser = parse_html(sys.argv[1])