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
16 from parse_html_beautifulsoup import parse_html
20 parsers.append(parse_html)
22 from parse_html_htmlparser import parse_html
23 parsers.append(parse_html)
27 entity_re = re.compile("(&#[0-9]+;)")
29 def recode_entities(title, charset):
31 for part in entity_re.split(title):
32 if entity_re.match(part):
33 part = unichr(int(part[2:-1])).encode(charset, "replace")
36 return ''.join(output)
39 def parse_html(filename, charset=None, log=None):
42 codecs.lookup(charset) # In case of unknown charset...
43 except (ValueError, LookupError):
44 charset = None # ...try charset from HTML
47 parser = p(filename, charset)
51 if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
54 if not parser.charset:
56 unicode(title, "ascii")
57 except UnicodeDecodeError:
58 parser.charset = DEFAULT_CHARSET
61 parser.charset = parser.charset.replace("windows-", "cp").lower()
63 if parser.charset and (parser.charset <> current_charset):
65 if parser.meta_charset:
66 if log: log(" META charset : %s" % parser.charset)
68 if log: log(" HTTP charset : %s" % parser.charset)
69 if log: log(" current charset: %s" % current_charset)
70 if log: log(" title : %s" % title)
73 title = unicode(title, parser.charset).encode(current_charset)
75 if parser.meta_charset and parser.charset.endswith("1252") and \
76 not DEFAULT_CHARSET.endswith("1252") and (DEFAULT_CHARSET <> current_charset):
77 parser.charset = DEFAULT_CHARSET
78 if log: log(" incorrect conversion from cp1252, converting from %s" % DEFAULT_CHARSET)
79 title = unicode(save_title, DEFAULT_CHARSET, "replace").encode(current_charset, "replace")
81 title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
82 if log: log(" converted title: %s" % title)
84 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
86 title = recode_entities(title, current_charset)
87 title = title.replace('\r', '').replace('\n', ' ').strip()
88 if log: log(" final title : %s" % title)
93 if __name__ == '__main__':
95 parser = parse_html(sys.argv[1], current_charset)