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