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
88 if not isinstance(part, basestring):
90 parts.append(part.strip())
91 title = ''.join(parts)
93 meta = head.find(_find_contenttype, recursive=False)
96 meta_content = meta.get("content")
98 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
101 except IndexError: # No charset in the META Content-Type
104 meta_charset = _charset == __charset
108 if _charset or meta_charset:
109 title = title.encode(_charset or meta_charset)
111 meta = head.find(_find_refresh, recursive=False)
113 refresh = meta.get("content")
117 meta = head.find(_find_icon, recursive=False)
119 icon = meta.get("href")
123 return HTMLParser(_charset, meta_charset, title, refresh, icon)
125 def _find_contenttype(Tag):
126 return (Tag.name == "meta") and \
127 (Tag.get("http-equiv", '').lower() == "content-type")
129 def _find_refresh(Tag):
130 return (Tag.name == "meta") and \
131 (Tag.get("http-equiv", '').lower() == "refresh")
134 return (Tag.name == "link") and \
135 (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))