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']
17 from ..compat import unicode
20 from . import bkmk_ph_beautifulsoup4
24 bkmk_ph_beautifulsoup4.DEFAULT_CHARSET = DEFAULT_CHARSET
25 parsers.append(bkmk_ph_beautifulsoup4.parse_html)
28 from . import bkmk_ph_beautifulsoup
32 bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
33 parsers.append(bkmk_ph_beautifulsoup.parse_html)
36 from . import bkmk_ph_html5
40 parsers.append(bkmk_ph_html5.parse_html)
43 from . import bkmk_ph_lxml
47 parsers.append(bkmk_ph_lxml.parse_html)
50 from . import bkmk_ph_htmlparser
54 parsers.append(bkmk_ph_htmlparser.parse_html)
56 # ElementTidy often segfaults
58 # from . import bkmk_ph_etreetidy
62 # parsers.append(bkmk_ph_etreetidy.parse_html)
65 from htmlentitydefs import name2codepoint
67 universal_charset = "utf-8"
68 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
72 entity_re = re.compile("(&\w+;)")
73 num_entity_re = re.compile("(&#[0-9]+;)")
76 def recode_entities(title, charset):
78 for part in entity_re.split(title):
79 if part not in ("&", "<", ">", """) and \
80 entity_re.match(part):
81 _part = name2codepoint.get(part[1:-1], None)
83 part = unichr(_part).encode(charset)
85 title = ''.join(output)
88 for part in num_entity_re.split(title):
89 if num_entity_re.match(part):
91 part = unichr(int(part[2:-1])).encode(charset)
92 except UnicodeEncodeError:
93 pass # Leave the entity as is
96 return ''.join(output)
99 BKMK_DEBUG_HTML_PARSERS = os.environ.get("BKMK_DEBUG_HTML_PARSERS")
102 def parse_html(html_text, charset=None, log=None):
108 codecs.lookup(charset) # In case of unknown charset...
109 except (ValueError, LookupError):
110 charset = None # ...try charset from HTML
112 charsets = [universal_charset, DEFAULT_CHARSET]
114 charset = charset.lower().replace("windows-", "cp")
115 if charset in charsets:
116 charsets.remove(charset)
117 charsets.insert(0, charset)
119 if BKMK_DEBUG_HTML_PARSERS:
125 parser = p(html_text, c, log)
130 if BKMK_DEBUG_HTML_PARSERS:
131 if log: log(" Parser %s: ok" % p.__module__)
132 _parsers.append((p, parser))
135 if log: log(" Parser %s: fail" % p.__module__)
136 if not BKMK_DEBUG_HTML_PARSERS and parser:
139 if BKMK_DEBUG_HTML_PARSERS:
141 if log: log(" All parsers have failed")
144 if log: log(" All parsers have failed")
147 if BKMK_DEBUG_HTML_PARSERS:
148 p, parser = _parsers[0]
149 if log: log(" Using %s" % p.__module__)
152 if isinstance(title, unicode):
154 parser.title = title.encode(parser.charset)
157 parser.title = title.encode('ascii')
158 except UnicodeEncodeError:
160 parser.title = title.encode(DEFAULT_CHARSET)
161 except UnicodeEncodeError:
162 parser.title = title.encode(universal_charset)
163 parser.charset = universal_charset
165 parser.charset = DEFAULT_CHARSET
167 parser.charset = 'ascii'
169 converted_title = title = parser.title
170 if title and (not parser.charset):
172 title.decode("ascii")
173 except UnicodeDecodeError:
174 parser.charset = DEFAULT_CHARSET
177 parser.charset = parser.charset.lower().replace("windows-", "cp")
179 if title and parser.charset and (
180 (parser.charset != universal_charset) or
181 ((not charset) or (charset != parser.charset))):
183 if parser.meta_charset:
184 if log: log(" META charset : %s" % parser.charset)
185 elif (not charset) or (charset != parser.charset):
186 if log: log(" guessed charset: %s" % parser.charset)
187 # if log: log(" current charset: %s" % universal_charset)
188 if log: log(" title : %s" % title)
189 if parser.charset != universal_charset:
191 converted_title = title.decode(parser.charset).\
192 encode(universal_charset)
195 log(" incorrect conversion from %s,"
197 % (parser.charset, DEFAULT_CHARSET))
199 title.decode(DEFAULT_CHARSET, "replace").\
200 encode(universal_charset, "replace")
201 parser.charset = DEFAULT_CHARSET
202 if log and (converted_title != title):
203 log(" converted title: %s" % converted_title)
205 if log: log(" unknown charset: '%s'" % parser.charset)
207 if log: log(" title : %s" % title)
210 final_title = recode_entities(converted_title, universal_charset)
211 parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
212 final_title = ' '.join([s for s in parts if s])
213 if log and (final_title != converted_title):
214 log(" final title : %s" % final_title)
215 parser.title = final_title
218 if isinstance(icon, unicode):
220 parser.icon = icon.encode('ascii')
221 except UnicodeEncodeError:
223 parser.icon = icon.encode(parser.charset)
227 def parse_filename(filename, charset=None, log=None):
228 fp = open(filename, 'r')
230 parser = parse_html(fp.read(), charset=charset, log=log)