]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html_beautifulsoup.py
Fixed a bug - parse "HTTP-Equiv" without content.
[bookmarks_db.git] / Robots / parse_html_beautifulsoup.py
1 """
2    HTML Parser using BeautifulSoup
3
4    Written by Broytman. Copyright (C) 2007, 2008 PhiloSoft Design
5 """
6
7 import re
8 from sgmllib import SGMLParser, SGMLParseError
9 from HTMLParser import HTMLParser
10 from BeautifulSoup import BeautifulSoup, CData
11
12
13 class BSoupParser(HTMLParser):
14    def __init__(self, charset, meta, title, refresh, icon):
15       object.__init__(self)
16       self.charset = charset
17       self.meta_charset = meta
18       self.title = title
19       self.refresh = refresh
20       self.icon = icon
21
22
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."""
28          j = None
29          if self.rawdata[i:i+9] == '<![CDATA[':
30               k = self.rawdata.find(']]>', i)
31               if k == -1:
32                   k = len(self.rawdata)
33               data = self.rawdata[i+9:k]
34               j = k+3
35               self._toStringSubclass(data, CData)
36          else:
37              try:
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)
43                  if match:
44                      toHandle = self.rawdata[i:match.end()]
45                  else:
46                      toHandle = self.rawdata[i:]
47                  self.handle_data(toHandle)
48                  j = i + len(toHandle)
49          return j
50
51
52 def _parse_html(filename, charset):
53    infile = open(filename, 'r')
54    try:
55       return BadDeclParser(infile, fromEncoding=charset)
56    except TypeError:
57       return None
58    finally:
59       infile.close()
60
61 def parse_html(filename, charset=None, log=None):
62    root = _parse_html(filename, charset)
63    if root is None:
64       return None
65
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)
70       if root is None:
71          return None
72
73    html = root.html
74    if html is None:
75       html = root
76
77    head = html.head
78    if head is None:
79       head = html # Some sites put TITLE in HTML without HEAD
80
81    title = head.title
82    if (title is None) and (html is not head):
83       # Some sites put TITLE in HTML outside of HEAD
84       title = html.title
85
86    if title is None:
87       # Lookup TITLE in the root
88       title = root.title
89
90    if title is not None:
91       if title.string:
92          title = title.string.encode(_charset)
93       else:
94          parts = []
95          for part in title:
96             if not isinstance(part, basestring):
97                part = unicode(part)
98             parts.append(part.strip())
99          title = ''.join(parts).encode(_charset)
100
101    meta = head.find(_find_contenttype, recursive=False)
102    if meta:
103       try:
104          meta_content = meta.get("content")
105          if meta_content:
106              __charset = meta_content.lower().split('charset=')[1].split(';')[0]
107          else:
108              meta_charset = False
109       except IndexError: # No charset in the META Content-Type
110          meta_charset = False
111       else:
112          meta_charset = _charset == __charset
113    else:
114       meta_charset = False
115
116    meta = head.find(_find_refresh, recursive=False)
117    if meta:
118       refresh = meta.get("content")
119    else:
120       refresh = None
121
122    meta = head.find(_find_icon, recursive=False)
123    if meta:
124       icon = meta.get("href")
125    else:
126       icon = None
127
128    return BSoupParser(_charset, meta_charset, title, refresh, icon)
129
130 def _find_contenttype(Tag):
131    return (Tag.name == "meta") and \
132       (Tag.get("http-equiv", '').lower() == "content-type")
133
134 def _find_refresh(Tag):
135    return (Tag.name == "meta") and \
136       (Tag.get("http-equiv", '').lower() == "refresh")
137
138 def _find_icon(Tag):
139    return (Tag.name == "link") and \
140       (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))