2 HTML Parser using BeautifulSoup
4 Written by Broytman. Copyright (C) 2007-2010 PhiloSoft Design
8 from sgmllib import SGMLParser, SGMLParseError
9 from BeautifulSoup import BeautifulSoup, CData
10 from parse_html_util import HTMLParser
13 # http://groups.google.com/group/beautifulsoup/browse_thread/thread/69093cb0d3a3cf63
14 class BadDeclParser(BeautifulSoup):
15 def parse_declaration(self, i):
16 """Treat a bogus SGML declaration as raw data. Treat a CDATA
17 declaration as a CData object."""
19 if self.rawdata[i:i+9] == '<![CDATA[':
20 k = self.rawdata.find(']]>', i)
23 data = self.rawdata[i+9:k]
25 self._toStringSubclass(data, CData)
28 j = SGMLParser.parse_declaration(self, i)
29 except SGMLParseError:
30 # Could not parse the DOCTYPE declaration
31 # Try to just skip the actual declaration
32 match = re.search(r'<!DOCTYPE([^>]*?)>', self.rawdata[i:], re.MULTILINE|re.IGNORECASE)
34 toHandle = self.rawdata[i:match.end()]
36 toHandle = self.rawdata[i:]
37 self.handle_data(toHandle)
42 def _parse_html(filename, charset):
43 infile = open(filename, 'r')
45 return BadDeclParser(infile, fromEncoding=charset)
51 def parse_html(filename, charset=None, log=None):
52 root = _parse_html(filename, charset)
56 _charset = root.originalEncoding
57 if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"): # Replace default
58 _charset = DEFAULT_CHARSET
59 root = _parse_html(filename, _charset)
69 head = html # Some sites put TITLE in HTML without HEAD
72 if (title is None) and (html is not head):
73 # Some sites put TITLE in HTML outside of HEAD
77 # Lookup TITLE in the root
82 title = title.string.encode(_charset)
86 if not isinstance(part, basestring):
88 parts.append(part.strip())
89 title = ''.join(parts).encode(_charset)
91 meta = head.find(_find_contenttype, recursive=False)
94 meta_content = meta.get("content")
96 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
99 except IndexError: # No charset in the META Content-Type
102 meta_charset = _charset == __charset
106 meta = head.find(_find_refresh, recursive=False)
108 refresh = meta.get("content")
112 meta = head.find(_find_icon, recursive=False)
114 icon = meta.get("href")
118 return HTMLParser(_charset, meta_charset, title, refresh, icon)
120 def _find_contenttype(Tag):
121 return (Tag.name == "meta") and \
122 (Tag.get("http-equiv", '').lower() == "content-type")
124 def _find_refresh(Tag):
125 return (Tag.name == "meta") and \
126 (Tag.get("http-equiv", '').lower() == "refresh")
129 return (Tag.name == "link") and \
130 (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))