]> git.phdru.name Git - bookmarks_db.git/blob - parse_html/bkmk_ph_beautifulsoup4.py
Fix(parse_html): Fix BS4 parser: encode title to utf-8 as the last resort
[bookmarks_db.git] / parse_html / bkmk_ph_beautifulsoup4.py
1 """HTML Parser using BeautifulSoup4
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) 2017 PhiloSoft Design"
9 __license__ = "GNU GPL"
10
11 __all__ = ['parse_html']
12
13
14 import re
15 from bs4 import BeautifulSoup
16 from .bkmk_ph_util import HTMLParser
17
18 universal_charset = "utf-8"
19 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
20
21 def _parse_html(html_text, charset):
22     try:
23         return BeautifulSoup(html_text, from_encoding=charset)
24     except TypeError:
25         return None
26
27 def parse_html(html_text, charset=None, log=None):
28     root = _parse_html(html_text, charset)
29     if root is None:
30         return None
31
32     _charset = root.originalEncoding
33     html = root.html
34     if html is None:
35         html = root
36
37     head = html.head
38     if head is None:
39         head = html # Some sites put TITLE in HTML without HEAD
40
41     title = head.title
42     if (title is None) and (html is not head):
43         # Some sites put TITLE in HTML outside of HEAD
44         title = html.title
45
46     if title is None:
47         # Lookup TITLE in the root
48         title = root.title
49
50     if title is not None:
51         if title.string:
52             title = title.string
53         else:
54             parts = []
55             for part in title:
56                 if not isinstance(part, basestring):
57                     part = unicode(part)
58                 parts.append(part.strip())
59             title = ''.join(parts)
60
61     meta = head.find(_find_contenttype, recursive=False)
62     if meta:
63         try:
64             meta_content = meta.get("content")
65             if meta_content:
66                 __charset = meta_content.lower().split('charset=')[1].split(';')[0]
67             else:
68                 __charset = False
69         except IndexError: # No charset in the META Content-Type
70             meta_charset = False
71         else:
72             meta_charset = _charset = __charset
73     else:
74         meta_charset = False
75
76     if not meta_charset:
77         meta = head.find(_find_charset, recursive=False)
78         if meta:
79             meta_content = meta.get("charset")
80             if meta_content:
81                 meta_charset = _charset = meta_content.lower()
82
83     if title and (_charset or meta_charset):
84         try:
85             title = title.encode(_charset or meta_charset)
86         except LookupError:
87             title = title.encode(universal_charset)
88             _charset = universal_charset
89
90     meta = head.find(_find_refresh, recursive=False)
91     if meta:
92         refresh = meta.get("content")
93     else:
94         refresh = None
95
96     meta = head.find(_find_icon, recursive=False)
97     if meta:
98         icon = meta.get("href")
99     else:
100         icon = None
101
102     if (title is None) and (refresh is None) and (icon is None):
103         return None
104     return HTMLParser(_charset, meta_charset, title, refresh, icon)
105
106 def _find_contenttype(Tag):
107     return (Tag.name == "meta") and \
108        (Tag.get_attribute_list("http-equiv", '')[0].lower() == "content-type")
109
110 def _find_charset(Tag):
111     return (Tag.name == "meta") and Tag.get("charset", '')
112
113 def _find_refresh(Tag):
114     return (Tag.name == "meta") and \
115        (Tag.get_attribute_list("http-equiv", '')[0].lower() == "refresh")
116
117 def _find_icon(Tag):
118     return (Tag.name == "link") and \
119        (Tag.get_attribute_list("rel", '')[0].lower() in ('icon', 'shortcut icon'))