]> git.phdru.name Git - bookmarks_db.git/commitdiff
Added BadDeclParser.
authorOleg Broytman <phd@phdru.name>
Sat, 22 Dec 2007 16:58:32 +0000 (16:58 +0000)
committerOleg Broytman <phd@phdru.name>
Sat, 22 Dec 2007 16:58:32 +0000 (16:58 +0000)
git-svn-id: file:///home/phd/archive/SVN/bookmarks_db/trunk@122 fdd5c36f-1aea-0310-aeeb-c58d7e2b6c23

Robots/parse_html_beautifulsoup.py

index 3408def7162a50deec9fee0f4894fdff5e37c9ea..5f010ad698e894e63d86515fa2a0111ad926da4d 100644 (file)
@@ -4,8 +4,10 @@
    Written by BroytMann. Copyright (C) 2007 PhiloSoft Design
 """
 
+import re
+from sgmllib import SGMLParser, SGMLParseError
 from HTMLParser import HTMLParser
-from BeautifulSoup import BeautifulSoup
+from BeautifulSoup import BeautifulSoup, CData
 
 
 class BSoupParser(HTMLParser):
@@ -18,10 +20,39 @@ class BSoupParser(HTMLParser):
       self.icon = icon
 
 
+# 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=None):
    infile = open(filename, 'r')
    try:
-      root = BeautifulSoup(infile, fromEncoding=charset)
+      root = BadDeclParser(infile, fromEncoding=charset)
    except TypeError:
       return None
    infile.close()