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_beautifulsoup
32 bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
33 parsers.append(bkmk_ph_beautifulsoup.parse_html)
36 from . import bkmk_ph_beautifulsoup4
40 bkmk_ph_beautifulsoup4.DEFAULT_CHARSET = DEFAULT_CHARSET
41 parsers.append(bkmk_ph_beautifulsoup4.parse_html)
44 from . import bkmk_ph_htmlparser
48 parsers.append(bkmk_ph_htmlparser.parse_html)
51 from . import bkmk_ph_lxml
55 parsers.append(bkmk_ph_lxml.parse_html)
57 universal_charset = "utf-8"
58 entity_re = re.compile("(&\\w+;)")
59 num_entity_re = re.compile("(&#[0-9]+;)")
62 def recode_entities(title, charset):
64 for part in entity_re.split(title):
65 if part not in ("&", "<", ">", """) and \
66 entity_re.match(part):
67 _part = name2codepoint.get(part[1:-1], None)
71 title = ''.join(output)
74 for part in num_entity_re.split(title):
75 if num_entity_re.match(part):
77 part = unichr(int(part[2:-1]))
78 except UnicodeEncodeError:
79 pass # Leave the entity as is
82 return ''.join(output)
85 BKMK_DEBUG_HTML_PARSERS = os.environ.get("BKMK_DEBUG_HTML_PARSERS")
88 def parse_html(html_text, charset=None, log=None):
89 if not html_text or not parsers:
94 codecs.lookup(charset) # In case of unknown charset...
95 except (ValueError, LookupError):
96 charset = None # ...try charset from HTML
98 charsets = [universal_charset, DEFAULT_CHARSET]
100 charset = charset.lower().replace("windows-", "cp")
101 if charset in charsets:
102 charsets.remove(charset)
103 charsets.insert(0, charset)
105 if BKMK_DEBUG_HTML_PARSERS:
111 parser = p(html_text, c, log)
116 if BKMK_DEBUG_HTML_PARSERS:
117 if log: log(" Parser %s: ok" % p.__module__)
118 _parsers.append((p, parser))
121 if log: log(" Parser %s: fail" % p.__module__)
122 if not BKMK_DEBUG_HTML_PARSERS and parser:
125 if BKMK_DEBUG_HTML_PARSERS:
127 if log: log(" All parsers have failed")
130 if log: log(" All parsers have failed")
133 if BKMK_DEBUG_HTML_PARSERS:
134 p, parser = _parsers[0]
135 if log: log(" Using %s" % p.__module__)
137 #title = parser.title
138 #if isinstance(title, unicode):
140 # parser.title = title.encode(parser.charset)
143 # parser.title = title.encode('ascii')
144 # except UnicodeEncodeError:
146 # parser.title = title.encode(DEFAULT_CHARSET)
147 # except UnicodeEncodeError:
148 # parser.title = title.encode(universal_charset)
149 # parser.charset = universal_charset
151 # parser.charset = DEFAULT_CHARSET
153 # parser.charset = 'ascii'
155 converted_title = title = parser.title
156 if title and isinstance(title, bytes) and (not parser.charset):
158 title.decode("ascii")
159 except UnicodeDecodeError:
160 parser.charset = DEFAULT_CHARSET
163 parser.charset = parser.charset.lower().replace("windows-", "cp")
165 if title and parser.charset and (
166 (parser.charset != universal_charset) or
167 ((not charset) or (charset != parser.charset))):
169 if parser.meta_charset:
170 if log: log(" META charset : %s" % parser.charset)
171 elif (not charset) or (charset != parser.charset):
172 if log: log(" guessed charset: %s" % parser.charset)
173 # if log: log(" current charset: %s" % universal_charset)
174 if log: log(" title : %s" % title)
175 #if parser.charset != universal_charset:
177 # converted_title = title.decode(parser.charset).\
178 # encode(universal_charset)
179 # except UnicodeError:
181 # log(" incorrect conversion from %s,"
182 # "converting from %s"
183 # % (parser.charset, DEFAULT_CHARSET))
184 # converted_title = \
185 # title.decode(DEFAULT_CHARSET, "replace").\
186 # encode(universal_charset, "replace")
187 # parser.charset = DEFAULT_CHARSET
188 #if log and (converted_title != title):
189 # log(" converted title: %s" % converted_title)
191 if log: log(" unknown charset: '%s'" % parser.charset)
193 if log: log(" title : %s" % title)
196 final_title = recode_entities(converted_title, universal_charset)
197 parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
198 final_title = ' '.join([s for s in parts if s])
199 if log and (final_title != converted_title):
200 log(" final title : %s" % final_title)
201 parser.title = final_title
204 #if isinstance(icon, unicode):
206 # parser.icon = icon.encode('ascii')
207 # except UnicodeEncodeError:
209 # parser.icon = icon.encode(parser.charset)
213 def parse_filename(filename, charset=None, log=None):
214 fp = open(filename, 'rt', encoding=charset)
216 parser = parse_html(fp.read(), charset=charset, log=log)