3 This file is a part of Bookmarks database and Internet robot.
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 1997-2023 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['parse_html', 'parse_filename', 'universal_charset']
18 from html.entities import name2codepoint
20 from htmlentitydefs import name2codepoint
22 from compat import unicode, unichr
24 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
28 from . import bkmk_ph_beautifulsoup4
32 bkmk_ph_beautifulsoup4.DEFAULT_CHARSET = DEFAULT_CHARSET
33 parsers.append(bkmk_ph_beautifulsoup4.parse_html)
36 from . import bkmk_ph_beautifulsoup
40 bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
41 parsers.append(bkmk_ph_beautifulsoup.parse_html)
44 from . import bkmk_ph_html5
48 parsers.append(bkmk_ph_html5.parse_html)
51 from . import bkmk_ph_lxml
55 parsers.append(bkmk_ph_lxml.parse_html)
58 from . import bkmk_ph_htmlparser
62 parsers.append(bkmk_ph_htmlparser.parse_html)
64 # ElementTidy often segfaults
66 # from . import bkmk_ph_etreetidy
70 # parsers.append(bkmk_ph_etreetidy.parse_html)
72 universal_charset = "utf-8"
73 entity_re = re.compile("(&\\w+;)")
74 num_entity_re = re.compile("(&#[0-9]+;)")
77 def recode_entities(title, charset):
79 for part in entity_re.split(title):
80 if part not in ("&", "<", ">", """) and \
81 entity_re.match(part):
82 _part = name2codepoint.get(part[1:-1], None)
86 title = ''.join(output)
89 for part in num_entity_re.split(title):
90 if num_entity_re.match(part):
92 part = unichr(int(part[2:-1]))
93 except UnicodeEncodeError:
94 pass # Leave the entity as is
97 return ''.join(output)
100 BKMK_DEBUG_HTML_PARSERS = os.environ.get("BKMK_DEBUG_HTML_PARSERS")
103 def parse_html(html_text, charset=None, log=None):
109 codecs.lookup(charset) # In case of unknown charset...
110 except (ValueError, LookupError):
111 charset = None # ...try charset from HTML
113 charsets = [universal_charset, DEFAULT_CHARSET]
115 charset = charset.lower().replace("windows-", "cp")
116 if charset in charsets:
117 charsets.remove(charset)
118 charsets.insert(0, charset)
120 if BKMK_DEBUG_HTML_PARSERS:
126 parser = p(html_text, c, log)
131 if BKMK_DEBUG_HTML_PARSERS:
132 if log: log(" Parser %s: ok" % p.__module__)
133 _parsers.append((p, parser))
136 if log: log(" Parser %s: fail" % p.__module__)
137 if not BKMK_DEBUG_HTML_PARSERS and parser:
140 if BKMK_DEBUG_HTML_PARSERS:
142 if log: log(" All parsers have failed")
145 if log: log(" All parsers have failed")
148 if BKMK_DEBUG_HTML_PARSERS:
149 p, parser = _parsers[0]
150 if log: log(" Using %s" % p.__module__)
152 #title = parser.title
153 #if isinstance(title, unicode):
155 # parser.title = title.encode(parser.charset)
158 # parser.title = title.encode('ascii')
159 # except UnicodeEncodeError:
161 # parser.title = title.encode(DEFAULT_CHARSET)
162 # except UnicodeEncodeError:
163 # parser.title = title.encode(universal_charset)
164 # parser.charset = universal_charset
166 # parser.charset = DEFAULT_CHARSET
168 # parser.charset = 'ascii'
170 converted_title = title = parser.title
171 if title and (not parser.charset):
173 title.decode("ascii")
174 except UnicodeDecodeError:
175 parser.charset = DEFAULT_CHARSET
178 parser.charset = parser.charset.lower().replace("windows-", "cp")
180 if title and parser.charset and (
181 (parser.charset != universal_charset) or
182 ((not charset) or (charset != parser.charset))):
184 if parser.meta_charset:
185 if log: log(" META charset : %s" % parser.charset)
186 elif (not charset) or (charset != parser.charset):
187 if log: log(" guessed charset: %s" % parser.charset)
188 # if log: log(" current charset: %s" % universal_charset)
189 if log: log(" title : %s" % title)
190 #if parser.charset != universal_charset:
192 # converted_title = title.decode(parser.charset).\
193 # encode(universal_charset)
194 # except UnicodeError:
196 # log(" incorrect conversion from %s,"
197 # "converting from %s"
198 # % (parser.charset, DEFAULT_CHARSET))
199 # converted_title = \
200 # title.decode(DEFAULT_CHARSET, "replace").\
201 # encode(universal_charset, "replace")
202 # parser.charset = DEFAULT_CHARSET
203 #if log and (converted_title != title):
204 # log(" converted title: %s" % converted_title)
206 if log: log(" unknown charset: '%s'" % parser.charset)
208 if log: log(" title : %s" % title)
211 final_title = recode_entities(converted_title, universal_charset)
212 parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
213 final_title = ' '.join([s for s in parts if s])
214 if log and (final_title != converted_title):
215 log(" final title : %s" % final_title)
216 parser.title = final_title
219 #if isinstance(icon, unicode):
221 # parser.icon = icon.encode('ascii')
222 # except UnicodeEncodeError:
224 # parser.icon = icon.encode(parser.charset)
228 def parse_filename(filename, charset=None, log=None):
229 fp = open(filename, 'r')
231 parser = parse_html(fp.read(), charset=charset, log=log)