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):
34 part = unichr(int(part[2:-1])).encode(charset)
35 except UnicodeEncodeError:
36 pass # Leave the entity as is
39 return ''.join(output)
42 def parse_html(filename, charset=None, log=None):
45 codecs.lookup(charset) # In case of unknown charset...
46 except (ValueError, LookupError):
47 charset = None # ...try charset from HTML
50 parser = p(filename, charset)
54 if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
57 if not parser.charset:
59 unicode(title, "ascii")
60 except UnicodeDecodeError:
61 parser.charset = DEFAULT_CHARSET
64 parser.charset = parser.charset.replace("windows-", "cp").lower()
66 if parser.charset and (parser.charset <> current_charset):
68 if parser.meta_charset:
69 if log: log(" META charset : %s" % parser.charset)
71 if log: log(" HTTP charset : %s" % parser.charset)
72 if log: log(" current charset: %s" % current_charset)
73 if log: log(" title : %s" % title)
76 title = unicode(title, parser.charset).encode(current_charset)
78 if parser.meta_charset and parser.charset.endswith("1252") and \
79 not DEFAULT_CHARSET.endswith("1252") and (DEFAULT_CHARSET <> current_charset):
80 parser.charset = DEFAULT_CHARSET
81 if log: log(" incorrect conversion from cp1252, converting from %s" % DEFAULT_CHARSET)
82 title = unicode(save_title, DEFAULT_CHARSET, "replace").encode(current_charset, "replace")
84 title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
85 if log: log(" converted title: %s" % title)
87 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
89 title = recode_entities(title, current_charset)
90 title = title.replace('\r', '').replace('\n', ' ').strip()
91 if log: log(" final title : %s" % title)
96 if __name__ == '__main__':
98 parser = parse_html(sys.argv[1], current_charset)