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 . import bkmk_ph_beautifulsoup4
22 bkmk_ph_beautifulsoup4.DEFAULT_CHARSET = DEFAULT_CHARSET
23 parsers.append(bkmk_ph_beautifulsoup4.parse_html)
26 from . import bkmk_ph_beautifulsoup
30 bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
31 parsers.append(bkmk_ph_beautifulsoup.parse_html)
34 from . import bkmk_ph_html5
38 parsers.append(bkmk_ph_html5.parse_html)
41 from . import bkmk_ph_lxml
45 parsers.append(bkmk_ph_lxml.parse_html)
48 from . import bkmk_ph_htmlparser
52 parsers.append(bkmk_ph_htmlparser.parse_html)
54 # ElementTidy often segfaults
56 # from . import bkmk_ph_etreetidy
60 # parsers.append(bkmk_ph_etreetidy.parse_html)
63 from htmlentitydefs import name2codepoint
65 universal_charset = "utf-8"
66 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
70 entity_re = re.compile("(&\w+;)")
71 num_entity_re = re.compile("(&#[0-9]+;)")
74 def recode_entities(title, charset):
76 for part in entity_re.split(title):
77 if part not in ("&", "<", ">", """) and \
78 entity_re.match(part):
79 _part = name2codepoint.get(part[1:-1], None)
81 part = unichr(_part).encode(charset)
83 title = ''.join(output)
86 for part in num_entity_re.split(title):
87 if num_entity_re.match(part):
89 part = unichr(int(part[2:-1])).encode(charset)
90 except UnicodeEncodeError:
91 pass # Leave the entity as is
94 return ''.join(output)
97 BKMK_DEBUG_HTML_PARSERS = os.environ.get("BKMK_DEBUG_HTML_PARSERS")
100 def parse_html(html_text, charset=None, log=None):
106 codecs.lookup(charset) # In case of unknown charset...
107 except (ValueError, LookupError):
108 charset = None # ...try charset from HTML
110 charsets = [universal_charset, DEFAULT_CHARSET]
112 charset = charset.lower().replace("windows-", "cp")
113 if charset in charsets:
114 charsets.remove(charset)
115 charsets.insert(0, charset)
117 if BKMK_DEBUG_HTML_PARSERS:
123 parser = p(html_text, c, log)
128 if BKMK_DEBUG_HTML_PARSERS:
129 if log: log(" Parser %s: ok" % p.__module__)
130 _parsers.append((p, parser))
133 if log: log(" Parser %s: fail" % p.__module__)
134 if not BKMK_DEBUG_HTML_PARSERS and parser:
137 if BKMK_DEBUG_HTML_PARSERS:
139 if log: log(" All parsers have failed")
142 if log: log(" All parsers have failed")
145 if BKMK_DEBUG_HTML_PARSERS:
146 p, parser = _parsers[0]
147 if log: log(" Using %s" % p.__module__)
150 if isinstance(title, unicode):
152 parser.title = title.encode(parser.charset)
155 parser.title = title.encode('ascii')
156 except UnicodeEncodeError:
158 parser.title = title.encode(DEFAULT_CHARSET)
159 except UnicodeEncodeError:
160 parser.title = title.encode(universal_charset)
161 parser.charset = universal_charset
163 parser.charset = DEFAULT_CHARSET
165 parser.charset = 'ascii'
167 converted_title = title = parser.title
168 if title and (not parser.charset):
170 unicode(title, "ascii")
171 except UnicodeDecodeError:
172 parser.charset = DEFAULT_CHARSET
175 parser.charset = parser.charset.lower().replace("windows-", "cp")
177 if title and parser.charset and (
178 (parser.charset != universal_charset) or
179 ((not charset) or (charset != parser.charset))):
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:
189 converted_title = unicode(title, parser.charset).\
190 encode(universal_charset)
193 log(" incorrect conversion from %s,"
195 % (parser.charset, DEFAULT_CHARSET))
197 unicode(title, DEFAULT_CHARSET, "replace").\
198 encode(universal_charset, "replace")
199 parser.charset = DEFAULT_CHARSET
200 if log and (converted_title != title):
201 log(" converted title: %s" % converted_title)
203 if log: log(" unknown charset: '%s'" % parser.charset)
205 if log: log(" title : %s" % title)
208 final_title = recode_entities(converted_title, universal_charset)
209 parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
210 final_title = ' '.join([s for s in parts if s])
211 if log and (final_title != converted_title):
212 log(" final title : %s" % final_title)
213 parser.title = final_title
216 if isinstance(icon, unicode):
218 parser.icon = icon.encode('ascii')
219 except UnicodeEncodeError:
221 parser.icon = icon.encode(parser.charset)
225 def parse_filename(filename, charset=None, log=None):
226 fp = open(filename, 'r')
228 parser = parse_html(fp.read(), charset=charset, log=log)