1 """HTML Parser using BeautifulSoup
3 This file is a part of Bookmarks database and Internet robot.
6 __version__ = "$Revision$"[11:-2]
7 __revision__ = "$Id$"[5:-2]
8 __date__ = "$Date$"[7:-2]
9 __author__ = "Oleg Broytman <phd@phdru.name>"
10 __copyright__ = "Copyright (C) 2007-2011 PhiloSoft Design"
11 __license__ = "GNU GPL"
13 __all__ = ['parse_html']
17 from sgmllib import SGMLParser, SGMLParseError
18 from BeautifulSoup import BeautifulSoup, CData
19 from .util import HTMLParser
22 # http://groups.google.com/group/beautifulsoup/browse_thread/thread/69093cb0d3a3cf63
23 class BadDeclParser(BeautifulSoup):
24 def parse_declaration(self, i):
25 """Treat a bogus SGML declaration as raw data. Treat a CDATA
26 declaration as a CData object."""
28 if self.rawdata[i:i+9] == '<![CDATA[':
29 k = self.rawdata.find(']]>', i)
32 data = self.rawdata[i+9:k]
34 self._toStringSubclass(data, CData)
37 j = SGMLParser.parse_declaration(self, i)
38 except SGMLParseError:
39 # Could not parse the DOCTYPE declaration
40 # Try to just skip the actual declaration
41 match = re.search(r'<!DOCTYPE([^>]*?)>', self.rawdata[i:], re.MULTILINE|re.IGNORECASE)
43 toHandle = self.rawdata[i:match.end()]
45 toHandle = self.rawdata[i:]
46 self.handle_data(toHandle)
51 def _parse_html(filename, charset):
52 infile = open(filename, 'r')
54 return BadDeclParser(infile, fromEncoding=charset)
60 def parse_html(filename, charset=None, log=None):
61 root = _parse_html(filename, charset)
65 _charset = root.originalEncoding
66 if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"): # Replace default
67 _charset = DEFAULT_CHARSET
68 root = _parse_html(filename, _charset)
78 head = html # Some sites put TITLE in HTML without HEAD
81 if (title is None) and (html is not head):
82 # Some sites put TITLE in HTML outside of HEAD
86 # Lookup TITLE in the root
97 if not isinstance(part, basestring):
99 parts.append(part.strip())
100 title = ''.join(parts)
102 meta = head.find(_find_contenttype, recursive=False)
105 meta_content = meta.get("content")
107 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
110 except IndexError: # No charset in the META Content-Type
113 meta_charset = _charset == __charset
117 if _charset or meta_charset:
118 title = title.encode(_charset or meta_charset)
120 meta = head.find(_find_refresh, recursive=False)
122 refresh = meta.get("content")
126 meta = head.find(_find_icon, recursive=False)
128 icon = meta.get("href")
132 return HTMLParser(_charset, meta_charset, title, refresh, icon)
134 def _find_contenttype(Tag):
135 return (Tag.name == "meta") and \
136 (Tag.get("http-equiv", '').lower() == "content-type")
138 def _find_refresh(Tag):
139 return (Tag.name == "meta") and \
140 (Tag.get("http-equiv", '').lower() == "refresh")
143 return (Tag.name == "link") and \
144 (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))