]> git.phdru.name Git - bookmarks_db.git/blob - parse_html/bkmk_ph_beautifulsoup.py
Style: Fix flake8 E302 expected 2 blank lines, found 1
[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 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
23
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(
43                     r'<!DOCTYPE([^>]*?)>', self.rawdata[i:],
44                     re.MULTILINE|re.IGNORECASE)  # noqa: E227
45                 #           missing whitespace around bitwise or shift operator
46                 if match:
47                     toHandle = self.rawdata[i:match.end()]
48                 else:
49                     toHandle = self.rawdata[i:]
50                 self.handle_data(toHandle)
51                 j = i + len(toHandle)
52         return j
53
54
55 def _parse_html(html_text, charset):
56     try:
57         return BadDeclParser(html_text, fromEncoding=charset)
58     except TypeError:
59         return None
60
61
62 def parse_html(html_text, charset=None, log=None):
63     root = _parse_html(html_text, charset)
64     if root is None:
65         return None
66
67     _charset = root.originalEncoding
68     if _charset in ("ISO-8859-2", "windows-1252", "MacCyrillic"):  # Replace default
69         _charset = DEFAULT_CHARSET
70         root = _parse_html(html_text, _charset)
71         if root is None:
72             return None
73
74     html = root.html
75     if html is None:
76         html = root
77
78     head = html.head
79     if head is None:
80         head = html  # Some sites put TITLE in HTML without HEAD
81
82     title = head.title
83     if (title is None) and (html is not head):
84         # Some sites put TITLE in HTML outside of HEAD
85         title = html.title
86
87     if title is None:
88         # Lookup TITLE in the root
89         title = root.title
90
91     if title is not None:
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 not meta_charset:
118         meta = head.find(_find_charset, recursive=False)
119         if meta:
120             meta_content = meta.get("charset")
121             if meta_content:
122                 meta_charset = _charset = meta_content.lower()
123
124     if title and (_charset or meta_charset):
125         title = title.encode(_charset or meta_charset)
126
127     meta = head.find(_find_refresh, recursive=False)
128     if meta:
129         refresh = meta.get("content")
130     else:
131         refresh = None
132
133     meta = head.find(_find_icon, recursive=False)
134     if meta:
135         icon = meta.get("href")
136     else:
137         icon = None
138
139     if (title is None) and (refresh is None) and (icon is None):
140         return None
141     return HTMLParser(_charset, meta_charset, title, refresh, icon)
142
143
144 def _find_contenttype(Tag):
145     return (Tag.name == "meta") and \
146        (Tag.get("http-equiv", '').lower() == "content-type")
147
148
149 def _find_charset(Tag):
150     return (Tag.name == "meta") and Tag.get("charset", '')
151
152
153 def _find_refresh(Tag):
154     return (Tag.name == "meta") and \
155        (Tag.get("http-equiv", '').lower() == "refresh")
156
157
158 def _find_icon(Tag):
159     return (Tag.name == "link") and \
160        (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))