]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
cbb45d612f9b33699b6f2d0bbe397b11a3562fe1
[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-2011 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
15 try:
16    import parse_html_beautifulsoup
17    parse_html_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
18 except ImportError:
19    pass
20 else:
21    parsers.append(parse_html_beautifulsoup.parse_html)
22
23 try:
24    from parse_html_lxml import parse_html
25 except ImportError:
26    pass
27 else:
28     parsers.append(parse_html)
29
30 try:
31    from parse_html_htmlparser import parse_html
32 except ImportError:
33    pass
34 else:
35     parsers.append(parse_html)
36
37 try:
38    import parse_html_html5
39 except ImportError:
40    pass
41 else:
42    parsers.append(parse_html_html5.parse_html)
43
44 # ElementTidy often segfaults
45 #try:
46 #   import parse_html_etreetidy
47 #except ImportError:
48 #   pass
49 #else:
50 #   parsers.append(parse_html_etreetidy.parse_html)
51
52 import re
53 from htmlentitydefs import name2codepoint
54
55 entity_re = re.compile("(&\w+;)")
56 num_entity_re = re.compile("(&#[0-9]+;)")
57
58 def recode_entities(title, charset):
59    output = []
60    for part in entity_re.split(title):
61       if part not in ("&", "<", ">", """) and \
62             entity_re.match(part):
63          _part = name2codepoint.get(part[1:-1], None)
64          if _part is not None:
65              part = unichr(_part).encode(charset)
66       output.append(part)
67    title = ''.join(output)
68
69    output = []
70    for part in num_entity_re.split(title):
71       if num_entity_re.match(part):
72          try:
73             part = unichr(int(part[2:-1])).encode(charset)
74          except UnicodeEncodeError:
75             pass # Leave the entity as is
76       output.append(part)
77
78    return ''.join(output)
79
80
81 def parse_html(filename, charset=None, log=None):
82    if not parsers:
83        return None
84
85    if charset:
86       try:
87          codecs.lookup(charset) # In case of unknown charset...
88       except (ValueError, LookupError):
89          charset = None         # ...try charset from HTML
90
91    charsets = [universal_charset, DEFAULT_CHARSET]
92    if charset:
93       charset = charset.lower().replace("windows-", "cp")
94       if charset in charsets:
95          charsets.remove(charset)
96       charsets.insert(0, charset)
97
98    for p in parsers:
99       parser = None
100       for c in charsets:
101          try:
102             parser = p(filename, c, log)
103             break
104          except UnicodeEncodeError:
105             pass
106       if parser:
107          break
108       else:
109          if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
110
111    if not parser:
112        return None
113
114    converted_title = title = parser.title
115    if title and (not parser.charset):
116       try:
117          unicode(title, "ascii")
118       except UnicodeDecodeError:
119          parser.charset = DEFAULT_CHARSET
120
121    if parser.charset:
122       parser.charset = parser.charset.lower().replace("windows-", "cp")
123
124    if title and parser.charset and (
125          (parser.charset <> universal_charset) or
126          ((not charset) or (charset <> parser.charset))):
127       try:
128          if parser.meta_charset:
129             if log: log("   META charset   : %s" % parser.charset)
130          elif (not charset) or (charset <> parser.charset):
131             if log: log("   guessed charset: %s" % parser.charset)
132          if log: log("   current charset: %s" % universal_charset)
133          if log: log("   title          : %s" % title)
134          if parser.charset <> universal_charset:
135             try:
136                converted_title = unicode(title, parser.charset).encode(universal_charset)
137             except UnicodeError:
138                if log: log("   incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
139                converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
140                parser.charset = DEFAULT_CHARSET
141          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
142       except LookupError:
143          if log: log("   unknown charset: '%s'" % parser.charset)
144    else:
145       if log: log("   title          : %s" % title)
146
147    if title:
148       final_title = recode_entities(converted_title, universal_charset)
149       parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
150       final_title = ' '.join([s for s in parts if s])
151       if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
152       parser.title = final_title
153
154    icon = parser.icon
155    if isinstance(icon, unicode):
156        try:
157            parser.icon = icon.encode('ascii')
158        except UnicodeEncodeError:
159            if parser.charset:
160                parser.icon = icon.encode(parser.charset)
161    return parser
162
163
164 if __name__ == '__main__':
165    import sys
166
167    l = len(sys.argv)
168    if l == 3:
169       filename = sys.argv[1]
170       charset = sys.argv[2]
171    elif l == 2:
172       filename = sys.argv[1]
173       charset = universal_charset
174    else:
175       sys.exit("Usage: %s filename [charset]" % sys.argv[0])
176
177    parser = parse_html(filename, charset, log=lambda s: sys.stdout.write(s + '\n'))
178    print "   refresh:", parser.refresh
179    print "   icon   :", parser.icon