@@ -423,6 +423,7 @@ class Selector:
423423 "_huge_tree" ,
424424 "root" ,
425425 "_text" ,
426+ "_text_lazy_html_root" ,
426427 "body" ,
427428 "__weakref__" ,
428429 ]
@@ -507,6 +508,10 @@ def __init__(
507508 self ._expr = _expr
508509 self ._huge_tree = huge_tree
509510 self ._text = text
511+ # self._text_to_html_root is used to store a temporary root node when
512+ # converting text to html for xpath queries. This is needed because
513+ # the text may not be valid html and we need to convert it to html
514+ self ._text_lazy_html_root = None
510515
511516 def __getstate__ (self ) -> Any :
512517 raise TypeError ("can't pickle Selector objects" )
@@ -606,7 +611,9 @@ def xpath(
606611 )
607612 else :
608613 try :
609- xpathev = self ._get_root (self ._text or "" , type = "html" ).xpath
614+ if self ._text_lazy_html_root is None :
615+ self ._text_lazy_html_root = self ._get_root (self ._text or "" , type = "html" )
616+ xpathev = self ._text_lazy_html_root .xpath
610617 except AttributeError :
611618 return typing .cast (
612619 SelectorList [_SelectorType ], self .selectorlist_cls ([])
@@ -625,7 +632,7 @@ def xpath(
625632 except etree .XPathError as exc :
626633 raise ValueError (f"XPath error: { exc } in { query } " )
627634
628- if type (result ) is not list :
635+ if not isinstance (result , list ) :
629636 result = [result ]
630637
631638 result = [
0 commit comments