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