3 This file is a part of Bookmarks database and Internet robot.
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 1997-2014 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_beautifulsoup
26 bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
27 parsers.append(bkmk_ph_beautifulsoup.parse_html)
30 from . import bkmk_ph_html5
34 parsers.append(bkmk_ph_html5.parse_html)
37 from . import bkmk_ph_lxml
41 parsers.append(bkmk_ph_lxml.parse_html)
44 from . import bkmk_ph_htmlparser
48 parsers.append(bkmk_ph_htmlparser.parse_html)
50 # ElementTidy often segfaults
52 # from . import bkmk_ph_etreetidy
56 # parsers.append(bkmk_ph_etreetidy.parse_html)
59 from htmlentitydefs import name2codepoint
61 entity_re = re.compile("(&\w+;)")
62 num_entity_re = re.compile("(&#[0-9]+;)")
64 def recode_entities(title, charset):
66 for part in entity_re.split(title):
67 if part not in ("&", "<", ">", """) and \
68 entity_re.match(part):
69 _part = name2codepoint.get(part[1:-1], None)
71 part = unichr(_part).encode(charset)
73 title = ''.join(output)
76 for part in num_entity_re.split(title):
77 if num_entity_re.match(part):
79 part = unichr(int(part[2:-1])).encode(charset)
80 except UnicodeEncodeError:
81 pass # Leave the entity as is
84 return ''.join(output)
88 BKMK_DEBUG_HTML_PARSERS = os.environ.get("BKMK_DEBUG_HTML_PARSERS")
90 def parse_html(html_text, charset=None, log=None):
96 codecs.lookup(charset) # In case of unknown charset...
97 except (ValueError, LookupError):
98 charset = None # ...try charset from HTML
100 charsets = [universal_charset, DEFAULT_CHARSET]
102 charset = charset.lower().replace("windows-", "cp")
103 if charset in charsets:
104 charsets.remove(charset)
105 charsets.insert(0, charset)
107 if BKMK_DEBUG_HTML_PARSERS:
113 parser = p(html_text, c, log)
118 if BKMK_DEBUG_HTML_PARSERS:
119 if log: log(" Parser %s: ok" % p.__module__)
120 _parsers.append((p, parser))
123 if log: log(" Parser %s: fail" % p.__module__)
124 if not BKMK_DEBUG_HTML_PARSERS and parser:
127 if BKMK_DEBUG_HTML_PARSERS:
129 if log: log(" All parsers have failed")
132 if log: log(" All parsers have failed")
135 if BKMK_DEBUG_HTML_PARSERS:
136 p, parser = _parsers[0]
137 if log: log(" Using %s" % p.__module__)
139 converted_title = title = parser.title
140 if title and (not parser.charset):
142 unicode(title, "ascii")
143 except UnicodeDecodeError:
144 parser.charset = DEFAULT_CHARSET
147 parser.charset = parser.charset.lower().replace("windows-", "cp")
149 if title and parser.charset and (
150 (parser.charset <> universal_charset) or
151 ((not charset) or (charset <> parser.charset))):
153 if parser.meta_charset:
154 if log: log(" META charset : %s" % parser.charset)
155 elif (not charset) or (charset <> parser.charset):
156 if log: log(" guessed charset: %s" % parser.charset)
157 #if log: log(" current charset: %s" % universal_charset)
158 if log: log(" title : %s" % title)
159 if parser.charset <> universal_charset:
161 converted_title = unicode(title, parser.charset).encode(universal_charset)
163 if log: log(" incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
164 converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
165 parser.charset = DEFAULT_CHARSET
166 if log and (converted_title <> title): log(" converted title: %s" % converted_title)
168 if log: log(" unknown charset: '%s'" % parser.charset)
170 if log: log(" title : %s" % title)
173 final_title = recode_entities(converted_title, universal_charset)
174 parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
175 final_title = ' '.join([s for s in parts if s])
176 if log and (final_title <> converted_title): log(" final title : %s" % final_title)
177 parser.title = final_title
180 if isinstance(icon, unicode):
182 parser.icon = icon.encode('ascii')
183 except UnicodeEncodeError:
185 parser.icon = icon.encode(parser.charset)
188 def parse_filename(filename, charset=None, log=None):
189 fp = open(filename, 'r')
191 parser = parse_html(fp.read(), charset=charset, log=log)