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 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
20 def _parse_html(html_text, charset):
22 return BeautifulSoup(html_text, from_encoding=charset)
26 def parse_html(html_text, charset=None, log=None):
27 root = _parse_html(html_text, charset)
31 _charset = root.originalEncoding
38 head = html # Some sites put TITLE in HTML without HEAD
41 if (title is None) and (html is not head):
42 # Some sites put TITLE in HTML outside of HEAD
46 # Lookup TITLE in the root
55 if not isinstance(part, basestring):
57 parts.append(part.strip())
58 title = ''.join(parts)
60 meta = head.find(_find_contenttype, recursive=False)
63 meta_content = meta.get("content")
65 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
68 except IndexError: # No charset in the META Content-Type
71 meta_charset = _charset = __charset
76 meta = head.find(_find_charset, recursive=False)
78 meta_content = meta.get("charset")
80 meta_charset = _charset = meta_content.lower()
82 if title and (_charset or meta_charset):
83 title = title.encode(_charset or meta_charset)
85 meta = head.find(_find_refresh, recursive=False)
87 refresh = meta.get("content")
91 meta = head.find(_find_icon, recursive=False)
93 icon = meta.get("href")
97 if (title is None) and (refresh is None) and (icon is None):
99 return HTMLParser(_charset, meta_charset, title, refresh, icon)
101 def _find_contenttype(Tag):
102 return (Tag.name == "meta") and \
103 (Tag.get_attribute_list("http-equiv", '')[0].lower() == "content-type")
105 def _find_charset(Tag):
106 return (Tag.name == "meta") and Tag.get("charset", '')
108 def _find_refresh(Tag):
109 return (Tag.name == "meta") and \
110 (Tag.get_attribute_list("http-equiv", '')[0].lower() == "refresh")
113 return (Tag.name == "link") and \
114 (Tag.get_attribute_list("rel", '')[0].lower() in ('icon', 'shortcut icon'))