1 """HTML Parser using BeautifulSoup4
3 This file is a part of Bookmarks database and Internet robot.
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 2017-2023 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['parse_html']
16 from bs4 import BeautifulSoup
18 from .bkmk_ph_util import HTMLParser
19 from compat import string_type
21 warnings.filterwarnings(
22 'ignore', 'No parser was explicitly specified')
23 warnings.filterwarnings(
25 "It looks like you're parsing an XML document using an HTML parser.")
27 universal_charset = "utf-8"
28 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
31 def _parse_html(html_text, charset):
33 if isinstance(html_text, bytes):
34 return BeautifulSoup(html_text, from_encoding=charset)
36 return BeautifulSoup(html_text)
41 def parse_html(html_text, charset=None, log=None):
44 root = _parse_html(html_text, charset)
48 _charset = root.originalEncoding
55 head = html # Some sites put TITLE in HTML without HEAD
58 if (title is None) and (html is not head):
59 # Some sites put TITLE in HTML outside of HEAD
63 # Lookup TITLE in the root
72 #if not isinstance(part, string_type):
73 # part = part.decode()
75 parts.append(part.strip())
77 parts.append(' ') # Skip tags, they're usually `<br>`
78 title = ''.join(parts)
80 meta = head.find(_find_contenttype, recursive=False)
83 meta_content = meta.get("content")
85 __charset = meta_content.lower().split('charset=')[1].\
89 except IndexError: # No charset in the META Content-Type
92 meta_charset = _charset = __charset
97 meta = head.find(_find_charset, recursive=False)
99 meta_content = meta.get("charset")
101 meta_charset = _charset = meta_content.lower()
103 #if title and (_charset or meta_charset):
105 # title = title.encode(_charset or meta_charset)
106 # except LookupError:
107 # title = title.encode(universal_charset)
108 # _charset = universal_charset
110 meta = head.find(_find_refresh, recursive=False)
112 refresh = meta.get("content")
116 meta = head.find(_find_icon, recursive=False)
118 icon = meta.get("href")
122 if (title is None) and (refresh is None) and (icon is None):
124 return HTMLParser(_charset, meta_charset, title, refresh, icon)
127 def _find_contenttype(Tag):
128 return (Tag.name == "meta") and \
129 (Tag.get_attribute_list("http-equiv", '')[0].lower() == "content-type")
132 def _find_charset(Tag):
133 return (Tag.name == "meta") and Tag.get("charset", '')
136 def _find_refresh(Tag):
137 return (Tag.name == "meta") and \
138 (Tag.get_attribute_list("http-equiv", '')[0].lower() == "refresh")
142 return (Tag.name == "link") and \
143 (Tag.get_attribute_list("rel", '')[0].lower()
144 in ('icon', 'shortcut icon'))