]> git.phdru.name Git - bookmarks_db.git/blobdiff - parse_html/bkmk_ph_beautifulsoup.py
Change parse_html to parse strings, not files
[bookmarks_db.git] / parse_html / bkmk_ph_beautifulsoup.py
index a0ef6af76a5c78dc061d24acbf95498b44912cec..a2f57157db0347d71592d6732259b380972e8001 100644 (file)
@@ -1,10 +1,11 @@
 """HTML Parser using BeautifulSoup
 
 This file is a part of Bookmarks database and Internet robot.
+
 """
 
 __author__ = "Oleg Broytman <phd@phdru.name>"
-__copyright__ = "Copyright (C) 2007-2012 PhiloSoft Design"
+__copyright__ = "Copyright (C) 2007-2014 PhiloSoft Design"
 __license__ = "GNU GPL"
 
 __all__ = ['parse_html']
@@ -46,24 +47,21 @@ class BadDeclParser(BeautifulSoup):
          return j
 
 
-def _parse_html(filename, charset):
-   infile = open(filename, 'r')
+def _parse_html(html_text, charset):
    try:
-      return BadDeclParser(infile, fromEncoding=charset)
+      return BadDeclParser(html_text, fromEncoding=charset)
    except TypeError:
       return None
-   finally:
-      infile.close()
 
-def parse_html(filename, charset=None, log=None):
-   root = _parse_html(filename, charset)
+def parse_html(html_text, charset=None, log=None):
+   root = _parse_html(html_text, charset)
    if root is None:
       return None
 
    _charset = root.originalEncoding
    if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"): # Replace default
       _charset = DEFAULT_CHARSET
-      root = _parse_html(filename, _charset)
+      root = _parse_html(html_text, _charset)
       if root is None:
          return None
 
@@ -110,6 +108,13 @@ def parse_html(filename, charset=None, log=None):
    else:
       meta_charset = False
 
+   if not meta_charset:
+      meta = head.find(_find_charset, recursive=False)
+      if meta:
+         meta_content = meta.get("charset")
+         if meta_content:
+            meta_charset = _charset = meta_content.lower()
+
    if title and (_charset or meta_charset):
       title = title.encode(_charset or meta_charset)
 
@@ -133,6 +138,9 @@ def _find_contenttype(Tag):
    return (Tag.name == "meta") and \
       (Tag.get("http-equiv", '').lower() == "content-type")
 
+def _find_charset(Tag):
+   return (Tag.name == "meta") and Tag.get("charset", '')
+
 def _find_refresh(Tag):
    return (Tag.name == "meta") and \
       (Tag.get("http-equiv", '').lower() == "refresh")