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