2 HTML Parser using BeautifulSoup
4 Written by BroytMann. Copyright (C) 2007 PhiloSoft Design
8 from sgmllib import SGMLParser, SGMLParseError
9 from HTMLParser import HTMLParser
10 from BeautifulSoup import BeautifulSoup, CData
13 class BSoupParser(HTMLParser):
14 def __init__(self, charset, meta, title, refresh, icon):
16 self.charset = charset
17 self.meta_charset = meta
19 self.refresh = refresh
23 # http://groups.google.com/group/beautifulsoup/browse_thread/thread/69093cb0d3a3cf63
24 class BadDeclParser(BeautifulSoup):
25 def parse_declaration(self, i):
26 """Treat a bogus SGML declaration as raw data. Treat a CDATA
27 declaration as a CData object."""
29 if self.rawdata[i:i+9] == '<![CDATA[':
30 k = self.rawdata.find(']]>', i)
33 data = self.rawdata[i+9:k]
35 self._toStringSubclass(data, CData)
38 j = SGMLParser.parse_declaration(self, i)
39 except SGMLParseError:
40 # Could not parse the DOCTYPE declaration
41 # Try to just skip the actual declaration
42 match = re.search(r'<!DOCTYPE([^>]*?)>', self.rawdata[i:], re.MULTILINE)
44 toHandle = self.rawdata[i:match.end()]
46 toHandle = self.rawdata[i:]
47 self.handle_data(toHandle)
52 def parse_html(filename, charset=None):
53 infile = open(filename, 'r')
55 root = BadDeclParser(infile, fromEncoding=charset)
61 _charset = root.originalEncoding
63 title = root.html.head.title.string.encode(_charset)
64 except AttributeError:
67 meta = root.html.head.find(_find_refresh, recursive=False)
69 refresh = meta.get("content")
73 meta = root.html.head.find(_find_icon, recursive=False)
75 icon = meta.get("href")
79 return BSoupParser(_charset, _charset != charset, title, refresh, icon)
81 def _find_refresh(Tag):
82 return (Tag.name == "meta") and \
83 (Tag.get("http-equiv", '').lower() == "refresh")
86 return (Tag.name == "link") and \
87 (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))