+"""HTML Parsers
+
+This file is a part of Bookmarks database and Internet robot.
+"""
+
+__version__ = "$Revision$"[11:-2]
+__revision__ = "$Id$"[5:-2]
+__date__ = "$Date$"[7:-2]
+__author__ = "Oleg Broytman <phd@phdru.name>"
+__copyright__ = "Copyright (C) 1997-2011 PhiloSoft Design"
+__license__ = "GNU GPL"
+
+__all__ = ['parse_html', 'universal_charset']
+
+
+import codecs
+
+universal_charset = "utf-8"
+DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
+
+parsers = []
+
+try:
+ from . import bkmk_ph_beautifulsoup
+except ImportError:
+ pass
+else:
+ bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
+ parsers.append(bkmk_ph_beautifulsoup.parse_html)
+
+try:
+ from . import bkmk_ph_lxml
+except ImportError:
+ pass
+else:
+ parsers.append(bkmk_ph_lxml.parse_html)
+
+try:
+ from . import bkmk_ph_htmlparser
+except ImportError:
+ pass
+else:
+ parsers.append(bkmk_ph_htmlparser.parse_html)
+
+try:
+ from . import bkmk_ph_html5
+except ImportError:
+ pass
+else:
+ parsers.append(bkmk_ph_html5.parse_html)
+
+# ElementTidy often segfaults
+#try:
+# from . import bkmk_ph_etreetidy
+#except ImportError:
+# pass
+#else:
+# parsers.append(bkmk_ph_etreetidy.parse_html)
+
+import re
+from htmlentitydefs import name2codepoint
+
+entity_re = re.compile("(&\w+;)")
+num_entity_re = re.compile("(&#[0-9]+;)")
+
+def recode_entities(title, charset):
+ output = []
+ for part in entity_re.split(title):
+ if part not in ("&", "<", ">", """) and \
+ entity_re.match(part):
+ _part = name2codepoint.get(part[1:-1], None)
+ if _part is not None:
+ part = unichr(_part).encode(charset)
+ output.append(part)
+ title = ''.join(output)
+
+ output = []
+ for part in num_entity_re.split(title):
+ if num_entity_re.match(part):
+ try:
+ part = unichr(int(part[2:-1])).encode(charset)
+ except UnicodeEncodeError:
+ pass # Leave the entity as is
+ output.append(part)
+
+ return ''.join(output)
+
+
+def parse_html(filename, charset=None, log=None):
+ if not parsers:
+ return None
+
+ if charset:
+ try:
+ codecs.lookup(charset) # In case of unknown charset...
+ except (ValueError, LookupError):
+ charset = None # ...try charset from HTML
+
+ charsets = [universal_charset, DEFAULT_CHARSET]
+ if charset:
+ charset = charset.lower().replace("windows-", "cp")
+ if charset in charsets:
+ charsets.remove(charset)
+ charsets.insert(0, charset)
+
+ for p in parsers:
+ parser = None
+ for c in charsets:
+ try:
+ parser = p(filename, c, log)
+ except UnicodeEncodeError:
+ pass
+ else:
+ break
+ if parser:
+ break
+ else:
+ if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
+
+ if not parser:
+ if log: log("All parser has failed.")
+ return None
+
+ if log: log(" Using %s" % p.__module__)
+
+ converted_title = title = parser.title
+ if title and (not parser.charset):
+ try:
+ unicode(title, "ascii")
+ except UnicodeDecodeError:
+ parser.charset = DEFAULT_CHARSET
+
+ if parser.charset:
+ parser.charset = parser.charset.lower().replace("windows-", "cp")
+
+ if title and parser.charset and (
+ (parser.charset <> universal_charset) or
+ ((not charset) or (charset <> parser.charset))):
+ try:
+ if parser.meta_charset:
+ if log: log(" META charset : %s" % parser.charset)
+ elif (not charset) or (charset <> parser.charset):
+ if log: log(" guessed charset: %s" % parser.charset)
+ #if log: log(" current charset: %s" % universal_charset)
+ if log: log(" title : %s" % title)
+ if parser.charset <> universal_charset:
+ try:
+ converted_title = unicode(title, parser.charset).encode(universal_charset)
+ except UnicodeError:
+ if log: log(" incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
+ converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
+ parser.charset = DEFAULT_CHARSET
+ if log and (converted_title <> title): log(" converted title: %s" % converted_title)
+ except LookupError:
+ if log: log(" unknown charset: '%s'" % parser.charset)
+ else:
+ if log: log(" title : %s" % title)
+
+ if title:
+ final_title = recode_entities(converted_title, universal_charset)
+ parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
+ final_title = ' '.join([s for s in parts if s])
+ if log and (final_title <> converted_title): log(" final title : %s" % final_title)
+ parser.title = final_title
+
+ icon = parser.icon
+ if isinstance(icon, unicode):
+ try:
+ parser.icon = icon.encode('ascii')
+ except UnicodeEncodeError:
+ if parser.charset:
+ parser.icon = icon.encode(parser.charset)
+ return parser