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 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['parse_html']
15 from bs4 import BeautifulSoup
16 from .bkmk_ph_util import HTMLParser
18 universal_charset = "utf-8"
19 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
21 def _parse_html(html_text, charset):
23 return BeautifulSoup(html_text, from_encoding=charset)
27 def parse_html(html_text, charset=None, log=None):
28 root = _parse_html(html_text, charset)
32 _charset = root.originalEncoding
39 head = html # Some sites put TITLE in HTML without HEAD
42 if (title is None) and (html is not head):
43 # Some sites put TITLE in HTML outside of HEAD
47 # Lookup TITLE in the root
56 if not isinstance(part, basestring):
58 parts.append(part.strip())
59 title = ''.join(parts)
61 meta = head.find(_find_contenttype, recursive=False)
64 meta_content = meta.get("content")
66 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
69 except IndexError: # No charset in the META Content-Type
72 meta_charset = _charset = __charset
77 meta = head.find(_find_charset, recursive=False)
79 meta_content = meta.get("charset")
81 meta_charset = _charset = meta_content.lower()
83 if title and (_charset or meta_charset):
85 title = title.encode(_charset or meta_charset)
87 title = title.encode(universal_charset)
88 _charset = universal_charset
90 meta = head.find(_find_refresh, recursive=False)
92 refresh = meta.get("content")
96 meta = head.find(_find_icon, recursive=False)
98 icon = meta.get("href")
102 if (title is None) and (refresh is None) and (icon is None):
104 return HTMLParser(_charset, meta_charset, title, refresh, icon)
106 def _find_contenttype(Tag):
107 return (Tag.name == "meta") and \
108 (Tag.get_attribute_list("http-equiv", '')[0].lower() == "content-type")
110 def _find_charset(Tag):
111 return (Tag.name == "meta") and Tag.get("charset", '')
113 def _find_refresh(Tag):
114 return (Tag.name == "meta") and \
115 (Tag.get_attribute_list("http-equiv", '')[0].lower() == "refresh")
118 return (Tag.name == "link") and \
119 (Tag.get_attribute_list("rel", '')[0].lower() in ('icon', 'shortcut icon'))