]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
Recode HTML entities.
[bookmarks_db.git] / Robots / parse_html.py
1 #! /usr/bin/env python
2 """
3    HTML Parsers wrapper
4
5    Written by BroytMann. Copyright (C) 1997-2007 PhiloSoft Design
6 """
7
8 import codecs
9
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
13
14 parsers = []
15 try:
16    from parse_html_beautifulsoup import parse_html
17 except ImportError:
18    pass
19 else:
20    parsers.append(parse_html)
21
22 from parse_html_htmlparser import parse_html
23 parsers.append(parse_html)
24
25
26 import re
27 from htmlentitydefs import entitydefs
28
29 entity_re = re.compile("(&\w+;)")
30 num_entity_re = re.compile("(&#[0-9]+;)")
31
32 def recode_entities(title, charset):
33    output = []
34
35    for part in num_entity_re.split(title):
36       if num_entity_re.match(part):
37          try:
38             part = unichr(int(part[2:-1])).encode(charset)
39          except UnicodeEncodeError:
40             pass # Leave the entity as is
41       output.append(part)
42
43    output2 = []
44    for part in entity_re.split(''.join(output)):
45       if entity_re.match(part):
46          part = entitydefs.get(part[1:-1], part)
47       output2.append(part)
48
49    return ''.join(output2)
50
51
52 def parse_html(filename, charset=None, log=None):
53    if charset:
54       try:
55          codecs.lookup(charset) # In case of unknown charset...
56       except (ValueError, LookupError):
57          charset = None         # ...try charset from HTML
58
59    for p in parsers:
60       parser = p(filename, charset)
61       if parser:
62          break
63       else:
64          if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
65
66    converted_title = title = parser.title
67    if not parser.charset:
68       try:
69          unicode(title, "ascii")
70       except UnicodeDecodeError:
71          parser.charset = DEFAULT_CHARSET
72
73    if parser.charset:
74       parser.charset = parser.charset.replace("windows-", "cp").lower()
75
76    if parser.charset and (parser.charset <> current_charset):
77       try:
78          if parser.meta_charset:
79             if log: log("   META charset   : %s" % parser.charset)
80          else:
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)
84          save_title = title
85          try:
86             converted_title = unicode(title, parser.charset).encode(current_charset)
87          except UnicodeError:
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")
93             else:
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)
96       except LookupError:
97          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
98    else:
99       if log: log("   title          : %s" % title)
100
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
106    return parser
107
108
109 if __name__ == '__main__':
110    import sys
111    parser = parse_html(sys.argv[1], current_charset)
112    print parser.charset
113    print parser.title
114    print parser.refresh
115    print parser.icon