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