]> git.phdru.name Git - bookmarks_db.git/blob - parse_html/bkmk_ph_lxml.py
Fix(parse_html): Do not parse empty strings
[bookmarks_db.git] / parse_html / bkmk_ph_lxml.py
1 """HTML Parser using lxml.html
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) 2010-2023 PhiloSoft Design"
9 __license__ = "GNU GPL"
10
11 __all__ = ['parse_html']
12
13
14 import re
15 from lxml.html import fromstring
16 from .bkmk_ph_util import HTMLParser
17
18
19 def parse_html(html_text, charset=None, log=None):
20     if not html_text:
21         return None
22     try:
23         html_tree = fromstring(html_text)
24     except ValueError as e:
25         if e.args[0].startswith(
26             'Unicode strings with encoding declaration are not supported.'
27             ' Please use bytes input'
28         ):
29             if not charset:
30                 match = re.search(
31                     '<\\?xml version="(\\d|.)+" encoding="([^"]+)"\\?>',
32                     html_text, re.U)
33                 if match:
34                     charset = match.group(2)
35             if charset:
36                 html_text = html_text.encode(charset)
37                 html_tree = fromstring(html_text)
38             else:
39                 return None
40         else:
41             raise
42
43     title = html_tree.findtext('head/title')
44     if title is None:
45         title = html_tree.findtext('title')
46
47     meta = html_tree.findall('head/meta')
48     for m in meta:
49         if m.get('http-equiv', '').lower() == 'content-type':
50             meta_content = m.get("content")
51             if meta_content:
52                 try:
53                     meta_charset = \
54                         meta_content.lower().split('charset=')[1].split(';')[0]
55                     break
56                 except IndexError:
57                     meta_charset = False
58         elif m.get('charset', ''):
59             meta_charset = m.get('charset').lower()
60             break
61     else:
62         meta_charset = False
63
64     #if title and (charset or meta_charset):
65     #    title = title.encode(charset or meta_charset)
66
67     for m in meta:
68         if m.get('http-equiv', '').lower() == 'refresh':
69             refresh = m.get("content")
70             break
71     else:
72         refresh = None
73
74     for link in html_tree.findall('head/link'):
75         if link.get('rel', '').lower() in ('icon', 'shortcut icon'):
76             icon = link.get("href")
77             break
78     else:
79         icon = None
80
81     if (title is None) and (refresh is None) and (icon is None):
82         return None
83     return HTMLParser(charset, meta_charset, title, refresh, icon)