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
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
74 def do_link(self, attrs):
78 for attrname, value in attrs:
80 value = value.strip().lower()
81 if (attrname == 'rel') and (value in ('icon', 'shortcut icon')):
83 elif attrname == 'href':
93 entity_re = re.compile("(&#[0-9]+;)")
95 def recode_entities(title, charset):
97 for part in entity_re.split(title):
98 if entity_re.match(part):
99 part = unichr(int(part[2:-1])).encode(charset, "replace")
102 return ''.join(output)
105 def parse_html(filename, charset=None, log=None):
106 infile = open(filename, 'r')
107 parser = HTMLParser(charset)
112 except (HTMLParseError, HTMLHeadDone):
119 except (HTMLParseError, HTMLHeadDone):
124 if not parser.charset:
126 unicode(title, "ascii")
127 except UnicodeDecodeError:
128 parser.charset = DEFAULT_CHARSET
131 parser.charset = parser.charset.replace("windows-", "cp").lower()
133 if parser.charset and (parser.charset <> current_charset):
135 if parser.meta_charset:
136 if log: log(" META charset : %s" % parser.charset)
138 if log: log(" charset : %s" % parser.charset)
139 if log: log(" title : %s" % title)
140 title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
141 if log: log(" current charset: %s" % current_charset)
142 if log: log(" converted title: %s" % title)
144 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
146 parser.title = recode_entities(title, current_charset)
150 if __name__ == '__main__':
152 parser = parse_html(sys.argv[1])