]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html_beautifulsoup.py
Test if m_lib is available.
[bookmarks_db.git] / Robots / parse_html_beautifulsoup.py
1 """
2    HTML Parser using BeautifulSoup
3
4    Written by Broytman. Copyright (C) 2007-2010 PhiloSoft Design
5 """
6
7 import re
8 from sgmllib import SGMLParser, SGMLParseError
9 from BeautifulSoup import BeautifulSoup, CData
10 from parse_html_util import HTMLParser
11
12
13 # http://groups.google.com/group/beautifulsoup/browse_thread/thread/69093cb0d3a3cf63
14 class BadDeclParser(BeautifulSoup):
15     def parse_declaration(self, i):
16          """Treat a bogus SGML declaration as raw data. Treat a CDATA
17          declaration as a CData object."""
18          j = None
19          if self.rawdata[i:i+9] == '<![CDATA[':
20               k = self.rawdata.find(']]>', i)
21               if k == -1:
22                   k = len(self.rawdata)
23               data = self.rawdata[i+9:k]
24               j = k+3
25               self._toStringSubclass(data, CData)
26          else:
27              try:
28                  j = SGMLParser.parse_declaration(self, i)
29              except SGMLParseError:
30                  # Could not parse the DOCTYPE declaration
31                  # Try to just skip the actual declaration
32                  match = re.search(r'<!DOCTYPE([^>]*?)>', self.rawdata[i:], re.MULTILINE|re.IGNORECASE)
33                  if match:
34                      toHandle = self.rawdata[i:match.end()]
35                  else:
36                      toHandle = self.rawdata[i:]
37                  self.handle_data(toHandle)
38                  j = i + len(toHandle)
39          return j
40
41
42 def _parse_html(filename, charset):
43    infile = open(filename, 'r')
44    try:
45       return BadDeclParser(infile, fromEncoding=charset)
46    except TypeError:
47       return None
48    finally:
49       infile.close()
50
51 def parse_html(filename, charset=None, log=None):
52    root = _parse_html(filename, charset)
53    if root is None:
54       return None
55
56    _charset = root.originalEncoding
57    if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"): # Replace default
58       _charset = DEFAULT_CHARSET
59       root = _parse_html(filename, _charset)
60       if root is None:
61          return None
62
63    html = root.html
64    if html is None:
65       html = root
66
67    head = html.head
68    if head is None:
69       head = html # Some sites put TITLE in HTML without HEAD
70
71    title = head.title
72    if (title is None) and (html is not head):
73       # Some sites put TITLE in HTML outside of HEAD
74       title = html.title
75
76    if title is None:
77       # Lookup TITLE in the root
78       title = root.title
79
80    if title is not None:
81       if title.string:
82          title = title.string.encode(_charset)
83       else:
84          parts = []
85          for part in title:
86             if not isinstance(part, basestring):
87                part = unicode(part)
88             parts.append(part.strip())
89          title = ''.join(parts).encode(_charset)
90
91    meta = head.find(_find_contenttype, recursive=False)
92    if meta:
93       try:
94          meta_content = meta.get("content")
95          if meta_content:
96              __charset = meta_content.lower().split('charset=')[1].split(';')[0]
97          else:
98              __charset = False
99       except IndexError: # No charset in the META Content-Type
100          meta_charset = False
101       else:
102          meta_charset = _charset == __charset
103    else:
104       meta_charset = False
105
106    meta = head.find(_find_refresh, recursive=False)
107    if meta:
108       refresh = meta.get("content")
109    else:
110       refresh = None
111
112    meta = head.find(_find_icon, recursive=False)
113    if meta:
114       icon = meta.get("href")
115    else:
116       icon = None
117
118    return HTMLParser(_charset, meta_charset, title, refresh, icon)
119
120 def _find_contenttype(Tag):
121    return (Tag.name == "meta") and \
122       (Tag.get("http-equiv", '').lower() == "content-type")
123
124 def _find_refresh(Tag):
125    return (Tag.name == "meta") and \
126       (Tag.get("http-equiv", '').lower() == "refresh")
127
128 def _find_icon(Tag):
129    return (Tag.name == "link") and \
130       (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))