5 Written by BroytMann. Copyright (C) 1997-2007 PhiloSoft Design
10 from m_lib.defenc import default_encoding
11 current_charset = default_encoding.replace("windows-", "cp")
12 DEFAULT_CHARSET = "cp1251" # 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
34 def do_meta(self, attrs):
38 for attrname, value in attrs:
41 if attrname == 'http-equiv':
42 http_equiv = value.lower()
43 elif attrname == 'content':
46 if (not self.charset) and (http_equiv == "content-type"):
48 # extract charset from "text/html; foo; charset=UTF-8; bar;"
49 self.charset = content.lower().split('charset=')[1].split(';')[0]
50 self.meta_charset = 1 # Remember that the charset was retrieved from
51 # META tag, not from the Content-Type header
55 if http_equiv == "refresh":
56 self.refresh = content
59 def start_title(self, attrs):
63 if not self.title: # use only the first title
64 self.title = self.accumulator
67 def do_link(self, attrs):
71 for attrname, value in attrs:
73 value = value.strip().lower()
74 if (attrname == 'rel') and (value.lower() in ('icon', 'shortcut icon')):
76 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])