]> git.phdru.name Git - bookmarks_db.git/blobdiff - Robots/parse_html_beautifulsoup.py
application/xhtml+xml is HTML, too.
[bookmarks_db.git] / Robots / parse_html_beautifulsoup.py
index 4f395a16507e58d5e9a600de00b9056cb2aeb94b..93a4d6fd9a2ba27ba0c1de2fdcdb3fe9971461c0 100644 (file)
@@ -1,13 +1,16 @@
 """
    HTML Parser using BeautifulSoup
 
-   Written by BroytMann. Copyright (C) 2007 PhiloSoft Design
+   Written by BroytMann. Copyright (C) 2007, 2008 PhiloSoft Design
 """
 
-from BeautifulSoup import BeautifulSoup
+import re
+from sgmllib import SGMLParser, SGMLParseError
+from HTMLParser import HTMLParser
+from BeautifulSoup import BeautifulSoup, CData
 
 
-class DummyParser(object):
+class BSoupParser(HTMLParser):
    def __init__(self, charset, meta, title, refresh, icon):
       object.__init__(self)
       self.charset = charset
@@ -16,39 +19,112 @@ class DummyParser(object):
       self.refresh = refresh
       self.icon = icon
 
-def parse_html(filename, charset=None):
+
+# http://groups.google.com/group/beautifulsoup/browse_thread/thread/69093cb0d3a3cf63
+class BadDeclParser(BeautifulSoup):
+    def parse_declaration(self, i):
+         """Treat a bogus SGML declaration as raw data. Treat a CDATA
+         declaration as a CData object."""
+         j = None
+         if self.rawdata[i:i+9] == '<![CDATA[':
+              k = self.rawdata.find(']]>', i)
+              if k == -1:
+                  k = len(self.rawdata)
+              data = self.rawdata[i+9:k]
+              j = k+3
+              self._toStringSubclass(data, CData)
+         else:
+             try:
+                 j = SGMLParser.parse_declaration(self, i)
+             except SGMLParseError:
+                 # Could not parse the DOCTYPE declaration
+                 # Try to just skip the actual declaration
+                 match = re.search(r'<!DOCTYPE([^>]*?)>', self.rawdata[i:], re.MULTILINE)
+                 if match:
+                     toHandle = self.rawdata[i:match.end()]
+                 else:
+                     toHandle = self.rawdata[i:]
+                 self.handle_data(toHandle)
+                 j = i + len(toHandle)
+         return j
+
+
+def _parse_html(filename, charset):
    infile = open(filename, 'r')
-   root = BeautifulSoup(infile, fromEncoding=charset)
-   infile.close()
+   try:
+      return BadDeclParser(infile, fromEncoding=charset)
+   except TypeError:
+      return None
+   finally:
+      infile.close()
+
+def parse_html(filename, charset=None, log=None):
+   root = _parse_html(filename, charset)
+
+   _charset = root.originalEncoding
+   if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"): # Replace default
+      _charset = DEFAULT_CHARSET
+      root = _parse_html(filename, _charset)
 
-   charset = root.originalEncoding
    try:
-      title = root.html.head.title.string.encode(charset)
+      html = root.html
    except AttributeError:
-      title = ''
+      if log: log("No HTML in root")
+      html = root
+
+   if html is None:
+      html = root
 
    try:
-      meta = root.html.head.find(_find_refresh, recursive=False)
+      head = html.head
    except AttributeError:
-      refresh = None
-   else:
-      if meta:
-         refresh = meta.get("content")
-      else:
-         refresh = None
+      if log: log("No HEAD in HTML")
+      head = html
+
+   if head is None:
+      head = html # Some sites put TITLE in HTML without HEAD
 
    try:
-      meta = root.html.head.find(_find_icon, recursive=False)
+      title = head.title.string.encode(_charset)
    except AttributeError:
-      icon = None
-   else:
-      if meta:
-         icon = meta.get("href")
+      title = '' # HEAD but no TITLE
+
+   if (not title) and (head is not html):
+      # Some sites put TITLE in HTML outside of HEAD
+
+      try:
+         title = html.title.string.encode(_charset)
+      except AttributeError:
+         title = '' # no TITLE in HTML too
+
+   meta = head.find(_find_contenttype, recursive=False)
+   if meta:
+      try:
+         __charset = meta.get("content").lower().split('charset=')[1].split(';')[0]
+      except IndexError: # No charset in the META Content-Type
+         meta_charset = False
       else:
-         icon = None
+         meta_charset = _charset == __charset
+   else:
+      meta_charset = False
+
+   meta = head.find(_find_refresh, recursive=False)
+   if meta:
+      refresh = meta.get("content")
+   else:
+      refresh = None
+
+   meta = head.find(_find_icon, recursive=False)
+   if meta:
+      icon = meta.get("href")
+   else:
+      icon = None
+
+   return BSoupParser(_charset, meta_charset, title, refresh, icon)
 
-   parser = DummyParser(charset, False, title, refresh, icon)
-   return parser
+def _find_contenttype(Tag):
+   return (Tag.name == "meta") and \
+      (Tag.get("http-equiv", '').lower() == "content-type")
 
 def _find_refresh(Tag):
    return (Tag.name == "meta") and \