2 HTML Parser using BeautifulSoup
4 Written by BroytMann. Copyright (C) 2007, 2008 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|re.I)
44 toHandle = self.rawdata[i:match.end()]
46 toHandle = self.rawdata[i:]
47 self.handle_data(toHandle)
52 def _parse_html(filename, charset):
53 infile = open(filename, 'r')
55 return BadDeclParser(infile, fromEncoding=charset)
61 def parse_html(filename, charset=None, log=None):
62 root = _parse_html(filename, charset)
66 _charset = root.originalEncoding
67 if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"): # Replace default
68 _charset = DEFAULT_CHARSET
69 root = _parse_html(filename, _charset)
75 except AttributeError:
76 if log: log("No HTML in root")
84 except AttributeError:
85 if log: log("No HEAD in HTML")
89 head = html # Some sites put TITLE in HTML without HEAD
92 title = head.title.string.encode(_charset)
93 except AttributeError:
94 title = '' # HEAD but no TITLE
96 if (not title) and (head is not html):
97 # Some sites put TITLE in HTML outside of HEAD
100 title = html.title.string.encode(_charset)
101 except AttributeError:
102 title = '' # no TITLE in HTML too
104 meta = head.find(_find_contenttype, recursive=False)
107 __charset = meta.get("content").lower().split('charset=')[1].split(';')[0]
108 except IndexError: # No charset in the META Content-Type
111 meta_charset = _charset == __charset
115 meta = head.find(_find_refresh, recursive=False)
117 refresh = meta.get("content")
121 meta = head.find(_find_icon, recursive=False)
123 icon = meta.get("href")
127 return BSoupParser(_charset, meta_charset, title, refresh, icon)
129 def _find_contenttype(Tag):
130 return (Tag.name == "meta") and \
131 (Tag.get("http-equiv", '').lower() == "content-type")
133 def _find_refresh(Tag):
134 return (Tag.name == "meta") and \
135 (Tag.get("http-equiv", '').lower() == "refresh")
138 return (Tag.name == "link") and \
139 (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))