]> git.phdru.name Git - bookmarks_db.git/blobdiff - Robots/parse_html.py
Fake headers to pretend this is a real browser.
[bookmarks_db.git] / Robots / parse_html.py
index 3250a0de5980c43a00c6cce8ff5e91a9e5b5471c..d3870fa210b8c3bdeefdac3c45d05aa13ec6cc1a 100755 (executable)
@@ -11,10 +11,16 @@ from m_lib.defenc import default_encoding
 current_charset = default_encoding.replace("windows-", "cp")
 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
 
+parsers = []
 try:
-   from parse_html_beautifulsoup import parse_html as _parse_html
+   from parse_html_beautifulsoup import parse_html
 except ImportError:
-   from parse_html_htmlparser import parse_html as _parse_html
+   pass
+else:
+   parsers.append(parse_html)
+
+from parse_html_htmlparser import parse_html
+parsers.append(parse_html)
 
 
 import re
@@ -24,7 +30,10 @@ def recode_entities(title, charset):
    output = []
    for part in entity_re.split(title):
       if entity_re.match(part):
-         part = unichr(int(part[2:-1])).encode(charset, "replace")
+         try:
+            part = unichr(int(part[2:-1])).encode(charset)
+         except UnicodeEncodeError:
+            pass # Leave the entity as is
       output.append(part)
 
    return ''.join(output)
@@ -37,9 +46,14 @@ def parse_html(filename, charset=None, log=None):
       except (ValueError, LookupError):
          charset = None         # ...try charset from HTML
 
-   parser = _parse_html(filename, charset)
-   title = parser.title
+   for p in parsers:
+      parser = p(filename, charset)
+      if parser:
+         break
+      else:
+         if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
 
+   title = parser.title
    if not parser.charset:
       try:
          unicode(title, "ascii")
@@ -72,7 +86,11 @@ def parse_html(filename, charset=None, log=None):
       except LookupError:
          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
 
-   parser.title = recode_entities(title, current_charset)
+   title = recode_entities(title, current_charset)
+   parts = [s.strip() for s in title.replace('\r', '').split('\n')]
+   title = ' '.join([s for s in parts if s])
+   if log: log("   final title    : %s" % title)
+   parser.title = title
    return parser