]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
Switched to utf-8.
[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-2008 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
13 universal_charset = "utf-8"
14 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
15
16 parsers = []
17 try:
18    from parse_html_beautifulsoup import parse_html
19 except ImportError:
20    pass
21 else:
22    parsers.append(parse_html)
23
24 from parse_html_htmlparser import parse_html
25 parsers.append(parse_html)
26
27
28 import re
29 from htmlentitydefs import entitydefs
30
31 entity_re = re.compile("(&\w+;)")
32 num_entity_re = re.compile("(&#[0-9]+;)")
33
34 def recode_entities(title, charset):
35    output = []
36    for part in num_entity_re.split(title):
37       if num_entity_re.match(part):
38          try:
39             part = unichr(int(part[2:-1])).encode(charset)
40          except UnicodeEncodeError:
41             pass # Leave the entity as is
42       output.append(part)
43
44    output2 = []
45    for part in entity_re.split(''.join(output)):
46       if entity_re.match(part):
47          part = entitydefs.get(part[1:-1], part)
48          if num_entity_re.match(part):
49             try:
50                part = unichr(int(part[2:-1])).encode(charset)
51             except UnicodeEncodeError:
52                pass # Leave the entity as is
53       output2.append(part)
54
55    return ''.join(output2)
56
57
58 def parse_html(filename, charset=None, log=None):
59    if charset:
60       try:
61          codecs.lookup(charset) # In case of unknown charset...
62       except (ValueError, LookupError):
63          charset = None         # ...try charset from HTML
64
65    for p in parsers:
66       parser = p(filename, charset)
67       if parser:
68          break
69       else:
70          if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
71
72    converted_title = title = parser.title
73    if not parser.charset:
74       try:
75          unicode(title, "ascii")
76       except UnicodeDecodeError:
77          parser.charset = DEFAULT_CHARSET
78
79    if parser.charset:
80       parser.charset = parser.charset.replace("windows-", "cp").lower()
81
82    if parser.charset and (parser.charset <> universal_charset):
83       try:
84          if parser.meta_charset:
85             if log: log("   META charset   : %s" % parser.charset)
86          else:
87             if log: log("   HTTP charset   : %s" % parser.charset)
88          if log: log("   current charset: %s" % universal_charset)
89          if log: log("   title          : %s" % title)
90          save_title = title
91          try:
92             converted_title = unicode(title, parser.charset).encode(universal_charset)
93          except UnicodeError:
94             if parser.meta_charset and parser.charset.endswith("1252") and \
95                   not DEFAULT_CHARSET.endswith("1252") and (DEFAULT_CHARSET <> universal_charset):
96                parser.charset = DEFAULT_CHARSET
97                if log: log("   incorrect conversion from cp1252, converting from %s" % DEFAULT_CHARSET)
98                converted_title = unicode(save_title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
99             else:
100                converted_title = unicode(title, parser.charset, "replace").encode(universal_charset, "replace")
101          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
102       except LookupError:
103          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, universal_charset))
104    else:
105       if log: log("   title          : %s" % title)
106
107    final_title = recode_entities(converted_title, universal_charset)
108    parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
109    final_title = ' '.join([s for s in parts if s])
110    if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
111    parser.title = final_title
112    return parser
113
114
115 if __name__ == '__main__':
116    import sys
117    parser = parse_html(sys.argv[1], universal_charset)
118    print parser.charset
119    print parser.title
120    print parser.title.decode(universal_charset).encode(current_charset, "replace")
121    print parser.refresh
122    print parser.icon