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