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']
14 from bs4 import BeautifulSoup
16 from .bkmk_ph_util import HTMLParser
17 from compat import string_type
19 universal_charset = "utf-8"
20 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
23 def _parse_html(html_text, charset):
25 return BeautifulSoup(html_text, from_encoding=charset)
30 def parse_html(html_text, charset=None, log=None):
31 root = _parse_html(html_text, charset)
35 _charset = root.originalEncoding
42 head = html # Some sites put TITLE in HTML without HEAD
45 if (title is None) and (html is not head):
46 # Some sites put TITLE in HTML outside of HEAD
50 # Lookup TITLE in the root
59 if not isinstance(part, string_type):
61 parts.append(part.strip())
62 title = ''.join(parts)
64 meta = head.find(_find_contenttype, recursive=False)
67 meta_content = meta.get("content")
69 __charset = meta_content.lower().split('charset=')[1].\
73 except IndexError: # No charset in the META Content-Type
76 meta_charset = _charset = __charset
81 meta = head.find(_find_charset, recursive=False)
83 meta_content = meta.get("charset")
85 meta_charset = _charset = meta_content.lower()
87 if title and (_charset or meta_charset):
89 title = title.encode(_charset or meta_charset)
91 title = title.encode(universal_charset)
92 _charset = universal_charset
94 meta = head.find(_find_refresh, recursive=False)
96 refresh = meta.get("content")
100 meta = head.find(_find_icon, recursive=False)
102 icon = meta.get("href")
106 if (title is None) and (refresh is None) and (icon is None):
108 return HTMLParser(_charset, meta_charset, title, refresh, icon)
111 def _find_contenttype(Tag):
112 return (Tag.name == "meta") and \
113 (Tag.get_attribute_list("http-equiv", '')[0].lower() == "content-type")
116 def _find_charset(Tag):
117 return (Tag.name == "meta") and Tag.get("charset", '')
120 def _find_refresh(Tag):
121 return (Tag.name == "meta") and \
122 (Tag.get_attribute_list("http-equiv", '')[0].lower() == "refresh")
126 return (Tag.name == "link") and \
127 (Tag.get_attribute_list("rel", '')[0].lower()
128 in ('icon', 'shortcut icon'))