]> git.phdru.name Git - bookmarks_db.git/blob - parse_html/bkmk_parse_html.py
Style: Fix flake8 E302 expected 2 blank lines, found 1
[bookmarks_db.git] / parse_html / bkmk_parse_html.py
1 """HTML Parsers
2
3 This file is a part of Bookmarks database and Internet robot.
4
5 """
6
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 1997-2023 PhiloSoft Design"
9 __license__ = "GNU GPL"
10
11 __all__ = ['parse_html', 'parse_filename', 'universal_charset']
12
13
14 import codecs
15
16 universal_charset = "utf-8"
17 DEFAULT_CHARSET = "cp1251"  # Stupid default for Russian Cyrillic
18
19 parsers = []
20
21 try:
22     from . import bkmk_ph_beautifulsoup4
23 except ImportError:
24     pass
25 else:
26     bkmk_ph_beautifulsoup4.DEFAULT_CHARSET = DEFAULT_CHARSET
27     parsers.append(bkmk_ph_beautifulsoup4.parse_html)
28
29 try:
30     from . import bkmk_ph_beautifulsoup
31 except ImportError:
32     pass
33 else:
34     bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
35     parsers.append(bkmk_ph_beautifulsoup.parse_html)
36
37 try:
38     from . import bkmk_ph_html5
39 except ImportError:
40     pass
41 else:
42     parsers.append(bkmk_ph_html5.parse_html)
43
44 try:
45     from . import bkmk_ph_lxml
46 except ImportError:
47     pass
48 else:
49     parsers.append(bkmk_ph_lxml.parse_html)
50
51 try:
52     from . import bkmk_ph_htmlparser
53 except ImportError:
54     pass
55 else:
56     parsers.append(bkmk_ph_htmlparser.parse_html)
57
58 # ElementTidy often segfaults
59 # try:
60 #     from . import bkmk_ph_etreetidy
61 # except ImportError:
62 #     pass
63 # else:
64 #     parsers.append(bkmk_ph_etreetidy.parse_html)
65
66 import re
67 from htmlentitydefs import name2codepoint
68
69 entity_re = re.compile("(&\w+;)")
70 num_entity_re = re.compile("(&#[0-9]+;)")
71
72
73 def recode_entities(title, charset):
74     output = []
75     for part in entity_re.split(title):
76         if part not in ("&amp;", "&lt;", "&gt;", "&quot;") and \
77               entity_re.match(part):
78             _part = name2codepoint.get(part[1:-1], None)
79             if _part is not None:
80                 part = unichr(_part).encode(charset)
81         output.append(part)
82     title = ''.join(output)
83
84     output = []
85     for part in num_entity_re.split(title):
86         if num_entity_re.match(part):
87             try:
88                 part = unichr(int(part[2:-1])).encode(charset)
89             except UnicodeEncodeError:
90                 pass  # Leave the entity as is
91         output.append(part)
92
93     return ''.join(output)
94
95
96 import os
97 BKMK_DEBUG_HTML_PARSERS = os.environ.get("BKMK_DEBUG_HTML_PARSERS")
98
99
100 def parse_html(html_text, charset=None, log=None):
101     if not parsers:
102         return None
103
104     if charset:
105         try:
106             codecs.lookup(charset)  # In case of unknown charset...
107         except (ValueError, LookupError):
108             charset = None         # ...try charset from HTML
109
110     charsets = [universal_charset, DEFAULT_CHARSET]
111     if charset:
112         charset = charset.lower().replace("windows-", "cp")
113         if charset in charsets:
114             charsets.remove(charset)
115         charsets.insert(0, charset)
116
117     if BKMK_DEBUG_HTML_PARSERS:
118         _parsers = []
119     for p in parsers:
120         parser = None
121         for c in charsets:
122             try:
123                 parser = p(html_text, c, log)
124             except UnicodeError:
125                 pass
126             else:
127                 if parser:
128                     if BKMK_DEBUG_HTML_PARSERS:
129                         if log: log("   Parser %s: ok" % p.__module__)
130                         _parsers.append((p, parser))
131                     break
132         else:
133             if log: log("   Parser %s: fail" % p.__module__)
134         if not BKMK_DEBUG_HTML_PARSERS and parser:
135             break
136
137     if BKMK_DEBUG_HTML_PARSERS:
138         if not _parsers:
139             if log: log("   All parsers have failed")
140             return None
141     elif not parser:
142         if log: log("   All parsers have failed")
143         return None
144
145     if BKMK_DEBUG_HTML_PARSERS:
146         p, parser = _parsers[0]
147     if log: log("   Using %s" % p.__module__)
148
149     title = parser.title
150     if isinstance(title, unicode):
151         if parser.charset:
152             parser.title = title.encode(parser.charset)
153         else:
154             try:
155                 parser.title = title.encode('ascii')
156             except UnicodeEncodeError:
157                 try:
158                     parser.title = title.encode(DEFAULT_CHARSET)
159                 except UnicodeEncodeError:
160                     parser.title = title.encode(universal_charset)
161                     parser.charset = universal_charset
162                 else:
163                     parser.charset = DEFAULT_CHARSET
164             else:
165                 parser.charset = 'ascii'
166
167     converted_title = title = parser.title
168     if title and (not parser.charset):
169         try:
170             unicode(title, "ascii")
171         except UnicodeDecodeError:
172             parser.charset = DEFAULT_CHARSET
173
174     if parser.charset:
175         parser.charset = parser.charset.lower().replace("windows-", "cp")
176
177     if title and parser.charset and (
178           (parser.charset != universal_charset) or
179           ((not charset) or (charset != parser.charset))):
180         try:
181             if parser.meta_charset:
182                 if log: log("   META charset   : %s" % parser.charset)
183             elif (not charset) or (charset != parser.charset):
184                 if log: log("   guessed charset: %s" % parser.charset)
185             # if log: log("   current charset: %s" % universal_charset)
186             if log: log("   title          : %s" % title)
187             if parser.charset != universal_charset:
188                 try:
189                     converted_title = unicode(title, parser.charset).encode(universal_charset)
190                 except UnicodeError:
191                     if log: log("   incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
192                     converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
193                     parser.charset = DEFAULT_CHARSET
194             if log and (converted_title != title): log("   converted title: %s" % converted_title)
195         except LookupError:
196             if log: log("   unknown charset: '%s'" % parser.charset)
197     else:
198         if log: log("   title          : %s" % title)
199
200     if title:
201         final_title = recode_entities(converted_title, universal_charset)
202         parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
203         final_title = ' '.join([s for s in parts if s])
204         if log and (final_title != converted_title): log("   final title    : %s" % final_title)
205         parser.title = final_title
206
207     icon = parser.icon
208     if isinstance(icon, unicode):
209         try:
210             parser.icon = icon.encode('ascii')
211         except UnicodeEncodeError:
212             if parser.charset:
213                 parser.icon = icon.encode(parser.charset)
214     return parser
215
216
217 def parse_filename(filename, charset=None, log=None):
218     fp = open(filename, 'r')
219     try:
220         parser = parse_html(fp.read(), charset=charset, log=log)
221     finally:
222         fp.close()
223     return parser