]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html_beautifulsoup.py
Log more parsers errors.
[bookmarks_db.git] / Robots / parse_html_beautifulsoup.py
1 """
2    HTML Parser using BeautifulSoup
3
4    Written by BroytMann. 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)
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=None, log=None):
53    infile = open(filename, 'r')
54    try:
55       root = BadDeclParser(infile, fromEncoding=charset)
56    except TypeError:
57       if log: log("TypeError")
58       return None
59    finally:
60       infile.close()
61
62    try:
63       head = root.html.head
64    except AttributeError:
65       if log: log("No HTML in root or no HEAD in HTML")
66       return None
67
68    if head is None:
69       head = root.html # Some sites put TITLE in HTML without HEAD
70
71    _charset = root.originalEncoding
72    if _charset == "windows-1252": # Replace default
73       _charset = DEFAULT_CHARSET
74
75    try:
76       title = head.title.string.encode(_charset)
77    except AttributeError:
78       title = '' # HEAD but no TITLE
79
80    if (not title) and (head is not root.html):
81       # Some sites put TITLE in HTML outside of HEAD
82
83       try:
84          title = root.html.title.string.encode(_charset)
85       except AttributeError:
86          title = '' # no TITLE in HTML too
87
88    meta = head.find(_find_contenttype, recursive=False)
89    if meta:
90       try:
91          __charset = meta.get("content").lower().split('charset=')[1].split(';')[0]
92       except IndexError: # No charset in the META Content-Type
93          meta_charset = False
94       else:
95          meta_charset = _charset == __charset
96    else:
97       meta_charset = False
98
99    meta = head.find(_find_refresh, recursive=False)
100    if meta:
101       refresh = meta.get("content")
102    else:
103       refresh = None
104
105    meta = head.find(_find_icon, recursive=False)
106    if meta:
107       icon = meta.get("href")
108    else:
109       icon = None
110
111    return BSoupParser(_charset, meta_charset, title, refresh, icon)
112
113 def _find_contenttype(Tag):
114    return (Tag.name == "meta") and \
115       (Tag.get("http-equiv", '').lower() == "content-type")
116
117 def _find_refresh(Tag):
118    return (Tag.name == "meta") and \
119       (Tag.get("http-equiv", '').lower() == "refresh")
120
121 def _find_icon(Tag):
122    return (Tag.name == "link") and \
123       (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))