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