]> git.phdru.name Git - bookmarks_db.git/blob - parse_html/bkmk_ph_beautifulsoup.py
Style: Fix flake8 E501 line too long
[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"):
69         # Replace with default and re-parse
70         _charset = DEFAULT_CHARSET
71         root = _parse_html(html_text, _charset)
72         if root is None:
73             return None
74
75     html = root.html
76     if html is None:
77         html = root
78
79     head = html.head
80     if head is None:
81         head = html  # Some sites put TITLE in HTML without HEAD
82
83     title = head.title
84     if (title is None) and (html is not head):
85         # Some sites put TITLE in HTML outside of HEAD
86         title = html.title
87
88     if title is None:
89         # Lookup TITLE in the root
90         title = root.title
91
92     if title is not None:
93         if title.string:
94             title = title.string
95         else:
96             parts = []
97             for part in title:
98                 if not isinstance(part, basestring):
99                     part = unicode(part)
100                 parts.append(part.strip())
101             title = ''.join(parts)
102
103     meta = head.find(_find_contenttype, recursive=False)
104     if meta:
105         try:
106             meta_content = meta.get("content")
107             if meta_content:
108                 __charset = meta_content.lower().split('charset=')[1].\
109                     split(';')[0]
110             else:
111                 __charset = False
112         except IndexError:  # No charset in the META Content-Type
113             meta_charset = False
114         else:
115             meta_charset = _charset == __charset
116     else:
117         meta_charset = False
118
119     if not meta_charset:
120         meta = head.find(_find_charset, recursive=False)
121         if meta:
122             meta_content = meta.get("charset")
123             if meta_content:
124                 meta_charset = _charset = meta_content.lower()
125
126     if title and (_charset or meta_charset):
127         title = title.encode(_charset or meta_charset)
128
129     meta = head.find(_find_refresh, recursive=False)
130     if meta:
131         refresh = meta.get("content")
132     else:
133         refresh = None
134
135     meta = head.find(_find_icon, recursive=False)
136     if meta:
137         icon = meta.get("href")
138     else:
139         icon = None
140
141     if (title is None) and (refresh is None) and (icon is None):
142         return None
143     return HTMLParser(_charset, meta_charset, title, refresh, icon)
144
145
146 def _find_contenttype(Tag):
147     return (Tag.name == "meta") and \
148        (Tag.get("http-equiv", '').lower() == "content-type")
149
150
151 def _find_charset(Tag):
152     return (Tag.name == "meta") and Tag.get("charset", '')
153
154
155 def _find_refresh(Tag):
156     return (Tag.name == "meta") and \
157        (Tag.get("http-equiv", '').lower() == "refresh")
158
159
160 def _find_icon(Tag):
161     return (Tag.name == "link") and \
162        (Tag.get("rel", '').lower() in ('icon', 'shortcut icon'))