1 """HTML Parser using BeautifulSoup
3 This file is a part of Bookmarks database and Internet robot.
6 __author__ = "Oleg Broytman <phd@phdru.name>"
7 __copyright__ = "Copyright (C) 2007-2012 PhiloSoft Design"
8 __license__ = "GNU GPL"
10 __all__ = ['parse_html']
14 from sgmllib import SGMLParser, SGMLParseError
15 from BeautifulSoup import BeautifulSoup, CData
16 from .bkmk_ph_util import HTMLParser
18 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
20 # http://groups.google.com/group/beautifulsoup/browse_thread/thread/69093cb0d3a3cf63
21 class BadDeclParser(BeautifulSoup):
22 def parse_declaration(self, i):
23 """Treat a bogus SGML declaration as raw data. Treat a CDATA
24 declaration as a CData object."""
26 if self.rawdata[i:i+9] == '<![CDATA[':
27 k = self.rawdata.find(']]>', i)
30 data = self.rawdata[i+9:k]
32 self._toStringSubclass(data, CData)
35 j = SGMLParser.parse_declaration(self, i)
36 except SGMLParseError:
37 # Could not parse the DOCTYPE declaration
38 # Try to just skip the actual declaration
39 match = re.search(r'<!DOCTYPE([^>]*?)>', self.rawdata[i:], re.MULTILINE|re.IGNORECASE)
41 toHandle = self.rawdata[i:match.end()]
43 toHandle = self.rawdata[i:]
44 self.handle_data(toHandle)
49 def _parse_html(filename, charset):
50 infile = open(filename, 'r')
52 return BadDeclParser(infile, fromEncoding=charset)
58 def parse_html(filename, charset=None, log=None):
59 root = _parse_html(filename, charset)
63 _charset = root.originalEncoding
64 if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"): # Replace default
65 _charset = DEFAULT_CHARSET
66 root = _parse_html(filename, _charset)
76 head = html # Some sites put TITLE in HTML without HEAD
79 if (title is None) and (html is not head):
80 # Some sites put TITLE in HTML outside of HEAD
84 # Lookup TITLE in the root
93 if not isinstance(part, basestring):
95 parts.append(part.strip())
96 title = ''.join(parts)
98 meta = head.find(_find_contenttype, recursive=False)
101 meta_content = meta.get("content")
103 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
106 except IndexError: # No charset in the META Content-Type
109 meta_charset = _charset == __charset
113 if title and (_charset or meta_charset):
114 title = title.encode(_charset or meta_charset)
116 meta = head.find(_find_refresh, recursive=False)
118 refresh = meta.get("content")
122 meta = head.find(_find_icon, recursive=False)
124 icon = meta.get("href")
128 if (title is None) and (refresh is None) and (icon is None):
130 return HTMLParser(_charset, meta_charset, title, refresh, icon)
132 def _find_contenttype(Tag):
133 return (Tag.name == "meta") and \
134 (Tag.get("http-equiv", '').lower() == "content-type")
136 def _find_refresh(Tag):
137 return (Tag.name == "meta") and \
138 (Tag.get("http-equiv", '').lower() == "refresh")
141 return (Tag.name == "link") and \
142 (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))