]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
Fixed parsing in case of unknown entity.
[bookmarks_db.git] / Robots / parse_html.py
1 #! /usr/bin/env python
2 """
3    HTML Parsers wrapper
4
5    Written by Broytman. 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 name2codepoint
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 ("&", "<", ">", """) and \
36             entity_re.match(part):
37          _part = name2codepoint.get(part[1:-1], None)
38          if _part is None:
39              _part = part
40          else:
41              _part = unichr(_part).encode(charset)
42       output.append(_part)
43    title = ''.join(output)
44
45    output = []
46    for part in num_entity_re.split(title):
47       if num_entity_re.match(part):
48          try:
49             part = unichr(int(part[2:-1])).encode(charset)
50          except UnicodeEncodeError:
51             pass # Leave the entity as is
52       output.append(part)
53
54    return ''.join(output)
55
56
57 def parse_html(filename, charset=None, log=None):
58    if charset:
59       try:
60          codecs.lookup(charset) # In case of unknown charset...
61       except (ValueError, LookupError):
62          charset = None         # ...try charset from HTML
63
64    charsets = [universal_charset, DEFAULT_CHARSET]
65    if charset:
66       charset = charset.lower().replace("windows-", "cp")
67       if charset not in charsets:
68          charsets.insert(0, charset)
69
70    for p in parsers:
71       parser = None
72       for c in charsets:
73          try:
74             parser = p(filename, c, log)
75             break
76          except UnicodeEncodeError:
77             pass
78       if parser:
79          break
80       else:
81          if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
82
83    converted_title = title = parser.title
84    if title and (not parser.charset):
85       try:
86          unicode(title, "ascii")
87       except UnicodeDecodeError:
88          parser.charset = DEFAULT_CHARSET
89
90    if parser.charset:
91       parser.charset = parser.charset.lower().replace("windows-", "cp")
92
93    if title and parser.charset and (
94          (parser.charset <> universal_charset) or
95          ((not charset) or (charset <> parser.charset))):
96       try:
97          if parser.meta_charset:
98             if log: log("   META charset   : %s" % parser.charset)
99          elif (not charset) or (charset <> parser.charset):
100             if log: log("   guessed charset: %s" % parser.charset)
101          if log: log("   current charset: %s" % universal_charset)
102          if log: log("   title          : %s" % title)
103          if parser.charset <> universal_charset:
104             try:
105                converted_title = unicode(title, parser.charset).encode(universal_charset)
106             except UnicodeError:
107                if log: log("   incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
108                converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
109                parser.charset = DEFAULT_CHARSET
110          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
111       except LookupError:
112          if log: log("   unknown charset: '%s'" % parser.charset)
113    else:
114       if log: log("   title          : %s" % title)
115
116    if title:
117       final_title = recode_entities(converted_title, universal_charset)
118       parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
119       final_title = ' '.join([s for s in parts if s])
120       if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
121       parser.title = final_title
122    return parser
123
124
125 if __name__ == '__main__':
126    import sys
127
128    l = len(sys.argv)
129    if l == 3:
130       filename = sys.argv[1]
131       charset = sys.argv[2]
132    elif l == 2:
133       filename = sys.argv[1]
134       charset = universal_charset
135    else:
136       sys.exit("Usage: %s filename [charset]" % sys.argv[0])
137
138    parser = parse_html(filename, charset, log=lambda s: sys.stdout.write(s + '\n'))
139    print "   refresh:", parser.refresh
140    print "   icon   :", parser.icon