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 .bkmk_ph_util import HTMLParser
21 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
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.IGNORECASE)
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)
79 head = html # Some sites put TITLE in HTML without HEAD
82 if (title is None) and (html is not head):
83 # Some sites put TITLE in HTML outside of HEAD
87 # Lookup TITLE in the root
98 if not isinstance(part, basestring):
100 parts.append(part.strip())
101 title = ''.join(parts)
103 meta = head.find(_find_contenttype, recursive=False)
106 meta_content = meta.get("content")
108 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
111 except IndexError: # No charset in the META Content-Type
114 meta_charset = _charset == __charset
118 if _charset or meta_charset:
119 title = title.encode(_charset or meta_charset)
121 meta = head.find(_find_refresh, recursive=False)
123 refresh = meta.get("content")
127 meta = head.find(_find_icon, recursive=False)
129 icon = meta.get("href")
133 return HTMLParser(_charset, meta_charset, title, refresh, icon)
135 def _find_contenttype(Tag):
136 return (Tag.name == "meta") and \
137 (Tag.get("http-equiv", '').lower() == "content-type")
139 def _find_refresh(Tag):
140 return (Tag.name == "meta") and \
141 (Tag.get("http-equiv", '').lower() == "refresh")
144 return (Tag.name == "link") and \
145 (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))