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"
14 from sgmllib import SGMLParser, SGMLParseError
15 from BeautifulSoup import BeautifulSoup, CData
16 from .util import HTMLParser
19 # http://groups.google.com/group/beautifulsoup/browse_thread/thread/69093cb0d3a3cf63
20 class BadDeclParser(BeautifulSoup):
21 def parse_declaration(self, i):
22 """Treat a bogus SGML declaration as raw data. Treat a CDATA
23 declaration as a CData object."""
25 if self.rawdata[i:i+9] == '<![CDATA[':
26 k = self.rawdata.find(']]>', i)
29 data = self.rawdata[i+9:k]
31 self._toStringSubclass(data, CData)
34 j = SGMLParser.parse_declaration(self, i)
35 except SGMLParseError:
36 # Could not parse the DOCTYPE declaration
37 # Try to just skip the actual declaration
38 match = re.search(r'<!DOCTYPE([^>]*?)>', self.rawdata[i:], re.MULTILINE|re.IGNORECASE)
40 toHandle = self.rawdata[i:match.end()]
42 toHandle = self.rawdata[i:]
43 self.handle_data(toHandle)
48 def _parse_html(filename, charset):
49 infile = open(filename, 'r')
51 return BadDeclParser(infile, fromEncoding=charset)
57 def parse_html(filename, charset=None, log=None):
58 root = _parse_html(filename, charset)
62 _charset = root.originalEncoding
63 if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"): # Replace default
64 _charset = DEFAULT_CHARSET
65 root = _parse_html(filename, _charset)
75 head = html # Some sites put TITLE in HTML without HEAD
78 if (title is None) and (html is not head):
79 # Some sites put TITLE in HTML outside of HEAD
83 # Lookup TITLE in the root
94 if not isinstance(part, basestring):
96 parts.append(part.strip())
97 title = ''.join(parts)
99 meta = head.find(_find_contenttype, recursive=False)
102 meta_content = meta.get("content")
104 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
107 except IndexError: # No charset in the META Content-Type
110 meta_charset = _charset == __charset
114 if _charset or meta_charset:
115 title = title.encode(_charset or meta_charset)
117 meta = head.find(_find_refresh, recursive=False)
119 refresh = meta.get("content")
123 meta = head.find(_find_icon, recursive=False)
125 icon = meta.get("href")
129 return HTMLParser(_charset, meta_charset, title, refresh, icon)
131 def _find_contenttype(Tag):
132 return (Tag.name == "meta") and \
133 (Tag.get("http-equiv", '').lower() == "content-type")
135 def _find_refresh(Tag):
136 return (Tag.name == "meta") and \
137 (Tag.get("http-equiv", '').lower() == "refresh")
140 return (Tag.name == "link") and \
141 (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))