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