X-Git-Url: https://git.phdru.name/?a=blobdiff_plain;f=parse_html%2Fbkmk_ph_lxml.py;h=24274826c52ee40179a83d96ff1eb07ceb60e6ec;hb=08ec9479b05db7a2d40cc58f3a39256dfaf9ff30;hp=03dd6f4c0d90bb60627a442d1dfb743eb7a07961;hpb=9e2bf3eaee5a8ee84c61ee5eac9c55090d45f63f;p=bookmarks_db.git diff --git a/parse_html/bkmk_ph_lxml.py b/parse_html/bkmk_ph_lxml.py index 03dd6f4..2427482 100644 --- a/parse_html/bkmk_ph_lxml.py +++ b/parse_html/bkmk_ph_lxml.py @@ -11,15 +11,34 @@ __license__ = "GNU GPL" __all__ = ['parse_html'] -from lxml.html import fromtring +import re +from lxml.html import fromstring from .bkmk_ph_util import HTMLParser def parse_html(html_text, charset=None, log=None): - html_tree = fromtring(html_text) - - if html_tree.getroot() is None: + if not html_text: return None + try: + html_tree = fromstring(html_text) + except ValueError as e: + if e.args[0].startswith( + 'Unicode strings with encoding declaration are not supported.' + ' Please use bytes input' + ): + if not charset: + match = re.search( + '<\\?xml version="(\\d|.)+" encoding="([^"]+)"\\?>', + html_text, re.U) + if match: + charset = match.group(2) + if charset: + html_text = html_text.encode(charset) + html_tree = fromstring(html_text) + else: + return None + else: + raise title = html_tree.findtext('head/title') if title is None: