5 Written by BroytMann. Copyright (C) 1997-2008 PhiloSoft Design
10 universal_charset = "utf-8"
11 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
15 import parse_html_beautifulsoup
16 parse_html_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
20 parsers.append(parse_html_beautifulsoup.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):
34 for part in entity_re.split(title):
35 if entity_re.match(part):
36 part = entitydefs.get(part[1:-1], part)
40 for part in num_entity_re.split(''.join(output)):
41 if num_entity_re.match(part):
43 part = unichr(int(part[2:-1])).encode(charset)
44 except UnicodeEncodeError:
45 pass # Leave the entity as is
48 return ''.join(output2)
51 def parse_html(filename, charset=None, log=None):
54 codecs.lookup(charset) # In case of unknown charset...
55 except (ValueError, LookupError):
56 charset = None # ...try charset from HTML
59 parser = p(filename, charset)
63 if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
65 converted_title = title = parser.title
66 if not parser.charset:
68 unicode(title, "ascii")
69 except UnicodeDecodeError:
70 parser.charset = DEFAULT_CHARSET
73 parser.charset = parser.charset.replace("windows-", "cp").lower()
75 if parser.charset and (parser.charset <> universal_charset):
77 if parser.meta_charset:
78 if log: log(" META charset : %s" % parser.charset)
80 if log: log(" HTTP charset : %s" % parser.charset)
81 if log: log(" current charset: %s" % universal_charset)
82 if log: log(" title : %s" % title)
84 converted_title = unicode(title, parser.charset).encode(universal_charset)
86 if log: log(" incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
87 converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
88 parser.charset = DEFAULT_CHARSET
89 if log and (converted_title <> title): log(" converted title: %s" % converted_title)
91 if log: log(" unknown charset: `%s' or `%s'" % (parser.charset, universal_charset))
93 if log: log(" title : %s" % title)
95 final_title = recode_entities(converted_title, universal_charset)
96 parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
97 final_title = ' '.join([s for s in parts if s])
98 if log and (final_title <> converted_title): log(" final title : %s" % final_title)
99 parser.title = final_title
103 if __name__ == '__main__':
105 from m_lib.defenc import default_encoding
106 current_charset = default_encoding.replace("windows-", "cp")
108 parser = parse_html(sys.argv[1], universal_charset)
111 print parser.title.decode(universal_charset).encode(current_charset, "replace")