From a32c7e779d7ab1f165cc0fe5430e1368929ae3c6 Mon Sep 17 00:00:00 2001 From: Jannis Leidel Date: Fri, 19 Aug 2011 18:13:21 +0200 Subject: [PATCH] Fixed LxmlParser. Closes #102. --- compressor/parser/lxml.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/compressor/parser/lxml.py b/compressor/parser/lxml.py index b74448b..8e26b2a 100644 --- a/compressor/parser/lxml.py +++ b/compressor/parser/lxml.py @@ -9,24 +9,28 @@ from compressor.utils.decorators import cached_property class LxmlParser(ParserBase): - @cached_property - def tree(self): - content = '%s' % self.content + def __init__(self, content): try: from lxml.html import fromstring, soupparser from lxml.etree import tostring + self.fromstring = fromstring + self.soupparser = soupparser self.tostring = tostring - tree = fromstring(content) - try: - ignore = tostring(tree, encoding=unicode) - except UnicodeDecodeError: - tree = soupparser.fromstring(content) except ImportError, err: raise ImproperlyConfigured("Error while importing lxml: %s" % err) except Exception, err: raise ParserError("Error while initializing Parser: %s" % err) - else: - return tree + super(LxmlParser, self).__init__(content) + + @cached_property + def tree(self): + content = '%s' % self.content + tree = self.fromstring(content) + try: + ignore = self.tostring(tree, encoding=unicode) + except UnicodeDecodeError: + tree = self.soupparser.fromstring(content) + return tree def css_elems(self): return self.tree.xpath('link[@rel="stylesheet"]|style')