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 from htmlentitydefs import entitydefs
29 entity_re = re.compile("(&\w+;)")
30 num_entity_re = re.compile("(&#[0-9]+;)")
32 def recode_entities(title, charset):
35 for part in num_entity_re.split(title):
36 if num_entity_re.match(part):
38 part = unichr(int(part[2:-1])).encode(charset)
39 except UnicodeEncodeError:
40 pass # Leave the entity as is
44 for part in entity_re.split(''.join(output)):
45 if entity_re.match(part):
46 part = entitydefs.get(part[1:-1], part)
49 return ''.join(output2)
52 def parse_html(filename, charset=None, log=None):
55 codecs.lookup(charset) # In case of unknown charset...
56 except (ValueError, LookupError):
57 charset = None # ...try charset from HTML
60 parser = p(filename, charset)
64 if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
66 converted_title = title = parser.title
67 if not parser.charset:
69 unicode(title, "ascii")
70 except UnicodeDecodeError:
71 parser.charset = DEFAULT_CHARSET
74 parser.charset = parser.charset.replace("windows-", "cp").lower()
76 if parser.charset and (parser.charset <> current_charset):
78 if parser.meta_charset:
79 if log: log(" META charset : %s" % parser.charset)
81 if log: log(" HTTP charset : %s" % parser.charset)
82 if log: log(" current charset: %s" % current_charset)
83 if log: log(" title : %s" % title)
86 converted_title = unicode(title, parser.charset).encode(current_charset)
88 if parser.meta_charset and parser.charset.endswith("1252") and \
89 not DEFAULT_CHARSET.endswith("1252") and (DEFAULT_CHARSET <> current_charset):
90 parser.charset = DEFAULT_CHARSET
91 if log: log(" incorrect conversion from cp1252, converting from %s" % DEFAULT_CHARSET)
92 converted_title = unicode(save_title, DEFAULT_CHARSET, "replace").encode(current_charset, "replace")
94 converted_title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
95 if log and (converted_title <> title): log(" converted title: %s" % converted_title)
97 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
99 if log: log(" title : %s" % title)
101 final_title = recode_entities(converted_title, current_charset)
102 parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
103 final_title = ' '.join([s for s in parts if s])
104 if log and (final_title <> converted_title): log(" final title : %s" % final_title)
105 parser.title = final_title
109 if __name__ == '__main__':
111 parser = parse_html(sys.argv[1], current_charset)