3 This file is a part of Bookmarks database and Internet robot.
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 1997-2017 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['parse_html', 'parse_filename', 'universal_charset']
16 universal_charset = "utf-8"
17 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
22 from . import bkmk_ph_beautifulsoup4
26 bkmk_ph_beautifulsoup4.DEFAULT_CHARSET = DEFAULT_CHARSET
27 parsers.append(bkmk_ph_beautifulsoup4.parse_html)
30 from . import bkmk_ph_beautifulsoup
34 bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
35 parsers.append(bkmk_ph_beautifulsoup.parse_html)
38 from . import bkmk_ph_html5
42 parsers.append(bkmk_ph_html5.parse_html)
45 from . import bkmk_ph_lxml
49 parsers.append(bkmk_ph_lxml.parse_html)
52 from . import bkmk_ph_htmlparser
56 parsers.append(bkmk_ph_htmlparser.parse_html)
58 # ElementTidy often segfaults
60 # from . import bkmk_ph_etreetidy
64 # parsers.append(bkmk_ph_etreetidy.parse_html)
67 from htmlentitydefs import name2codepoint
69 entity_re = re.compile("(&\w+;)")
70 num_entity_re = re.compile("(&#[0-9]+;)")
72 def recode_entities(title, charset):
74 for part in entity_re.split(title):
75 if part not in ("&", "<", ">", """) and \
76 entity_re.match(part):
77 _part = name2codepoint.get(part[1:-1], None)
79 part = unichr(_part).encode(charset)
81 title = ''.join(output)
84 for part in num_entity_re.split(title):
85 if num_entity_re.match(part):
87 part = unichr(int(part[2:-1])).encode(charset)
88 except UnicodeEncodeError:
89 pass # Leave the entity as is
92 return ''.join(output)
96 BKMK_DEBUG_HTML_PARSERS = os.environ.get("BKMK_DEBUG_HTML_PARSERS")
98 def parse_html(html_text, charset=None, log=None):
104 codecs.lookup(charset) # In case of unknown charset...
105 except (ValueError, LookupError):
106 charset = None # ...try charset from HTML
108 charsets = [universal_charset, DEFAULT_CHARSET]
110 charset = charset.lower().replace("windows-", "cp")
111 if charset in charsets:
112 charsets.remove(charset)
113 charsets.insert(0, charset)
115 if BKMK_DEBUG_HTML_PARSERS:
121 parser = p(html_text, c, log)
126 if BKMK_DEBUG_HTML_PARSERS:
127 if log: log(" Parser %s: ok" % p.__module__)
128 _parsers.append((p, parser))
131 if log: log(" Parser %s: fail" % p.__module__)
132 if not BKMK_DEBUG_HTML_PARSERS and parser:
135 if BKMK_DEBUG_HTML_PARSERS:
137 if log: log(" All parsers have failed")
140 if log: log(" All parsers have failed")
143 if BKMK_DEBUG_HTML_PARSERS:
144 p, parser = _parsers[0]
145 if log: log(" Using %s" % p.__module__)
148 if isinstance(title, unicode):
150 parser.title = title.encode(parser.charset)
153 parser.title = title.encode('ascii')
154 except UnicodeEncodeError:
155 parser.charset = DEFAULT_CHARSET
156 parser.title = title.encode(DEFAULT_CHARSET)
158 converted_title = title = parser.title
159 if title and (not parser.charset):
161 unicode(title, "ascii")
162 except UnicodeDecodeError:
163 parser.charset = DEFAULT_CHARSET
166 parser.charset = parser.charset.lower().replace("windows-", "cp")
168 if title and parser.charset and (
169 (parser.charset != universal_charset) or
170 ((not charset) or (charset != parser.charset))):
172 if parser.meta_charset:
173 if log: log(" META charset : %s" % parser.charset)
174 elif (not charset) or (charset != parser.charset):
175 if log: log(" guessed charset: %s" % parser.charset)
176 #if log: log(" current charset: %s" % universal_charset)
177 if log: log(" title : %s" % title)
178 if parser.charset != universal_charset:
180 converted_title = unicode(title, parser.charset).encode(universal_charset)
182 if log: log(" incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
183 converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
184 parser.charset = DEFAULT_CHARSET
185 if log and (converted_title != title): log(" converted title: %s" % converted_title)
187 if log: log(" unknown charset: '%s'" % parser.charset)
189 if log: log(" title : %s" % title)
192 final_title = recode_entities(converted_title, universal_charset)
193 parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
194 final_title = ' '.join([s for s in parts if s])
195 if log and (final_title != converted_title): log(" final title : %s" % final_title)
196 parser.title = final_title
199 if isinstance(icon, unicode):
201 parser.icon = icon.encode('ascii')
202 except UnicodeEncodeError:
204 parser.icon = icon.encode(parser.charset)
207 def parse_filename(filename, charset=None, log=None):
208 fp = open(filename, 'r')
210 parser = parse_html(fp.read(), charset=charset, log=log)