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