__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: