5 Written by BroytMann. Copyright (C) 1997-2007 PhiloSoft Design
8 from m_lib.defenc import default_encoding
9 current_charset = default_encoding.replace("windows-", "cp")
10 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
12 from HTMLParser import HTMLParseError
13 from m_lib.net.www.html import HTMLParser as _HTMLParser
16 class HTMLHeadDone(Exception): pass
19 class HTMLParser(_HTMLParser):
20 def __init__(self, charset=None):
21 _HTMLParser.__init__(self)
22 self.charset = charset
32 def do_meta(self, attrs):
36 for attrname, value in attrs:
39 if attrname == 'http-equiv':
40 http_equiv = value.lower()
41 elif attrname == 'content':
44 if (not self.charset) and (http_equiv == "content-type"):
46 # extract charset from "text/html; foo; charset=UTF-8; bar;"
47 self.charset = content.lower().split('charset=')[1].split(';')[0]
48 self.meta_charset = 1 # Remember that the charset was retrieved from
49 # META tag, not from the Content-Type header
53 if http_equiv == "refresh":
54 self.refresh = content
57 def start_title(self, attrs):
61 if not self.title: # use only the first title
62 self.title = self.accumulator
65 def do_link(self, attrs):
69 for attrname, value in attrs:
71 value = value.strip().lower()
72 if (attrname == 'rel') and (value in ('icon', 'shortcut icon')):
74 elif attrname == 'href':
84 entity_re = re.compile("(&#[0-9]+;)")
86 def recode_entities(title, charset):
88 for part in entity_re.split(title):
89 if entity_re.match(part):
90 part = unichr(int(part[2:-1])).encode(charset, "replace")
93 return ''.join(output)
96 def parse_html(filename, charset=None, log=None):
99 codecs.lookup(charset) # In case of unknown charset...
100 except (ValueError, LookupError):
101 charset = None # ...try charset from HTML
103 infile = open(filename, 'r')
104 parser = HTMLParser(charset)
109 except (HTMLParseError, HTMLHeadDone):
116 except (HTMLParseError, HTMLHeadDone):
121 if not parser.charset:
123 unicode(title, "ascii")
124 except UnicodeDecodeError:
125 parser.charset = DEFAULT_CHARSET
128 parser.charset = parser.charset.replace("windows-", "cp").lower()
130 if parser.charset and (parser.charset <> current_charset):
132 if parser.meta_charset:
133 if log: log(" META charset : %s" % parser.charset)
135 if log: log(" charset : %s" % parser.charset)
136 if log: log(" title : %s" % title)
137 title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
138 if log: log(" current charset: %s" % current_charset)
139 if log: log(" converted title: %s" % title)
141 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
143 parser.title = recode_entities(title, current_charset)
147 if __name__ == '__main__':
148 parser = parse_html(sys.argv[1])