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