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