From abebd6af421ac5436ffe532c892323fddca19fd2 Mon Sep 17 00:00:00 2001 From: Siraj saheb Date: Sun, 15 Nov 2026 19:33:58 +0530 Subject: [PATCH 1/3] avoid cubic ~ matching in xpath_indirect_adjacent_combinator a ~ b was translated to a/following-sibling::b. When many siblings match a, their following-sibling node-sets overlap, and libxml2 merges each one into the result with a linear duplicate scan, so matching was cubic in the number of siblings: li ~ li took 154 s on a list of 8000 items. The siblings after the first match of a in a sibling list include those after every later one, so only walk from that one, found with preceding-sibling::a[1], which stops at the nearest match. position() = 1 keeps the first match from each context node, which matters when the context node itself matches and has matching siblings before it, and in ~ chains. Only a plain name test is handled: a condition would have to be copied into the predicate, doubling the XPath at each nested :has() level. --- cssselect/xpath.py | 6 ++++++ tests/test_cssselect.py | 31 +++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/cssselect/xpath.py b/cssselect/xpath.py index 17e523f..3cd7271 100644 --- a/cssselect/xpath.py +++ b/cssselect/xpath.py @@ -560,6 +560,12 @@ def xpath_indirect_adjacent_combinator( self, left: XPathExpr, right: XPathExpr ) -> XPathExpr: """right is a sibling after left, immediately or not""" + if not left.condition: + # Only walk from the first left element among its siblings, or + # from the first one of each context node (e.g. itself). + left.condition = ( + f"position() = 1 or not(preceding-sibling::{left.element}[1])" + ) return left.join("/following-sibling::", right) # The relative selector is kept in `condition` (instead of being folded diff --git a/tests/test_cssselect.py b/tests/test_cssselect.py index e489161..2ebf5a8 100644 --- a/tests/test_cssselect.py +++ b/tests/test_cssselect.py @@ -962,11 +962,23 @@ def xpath(css: str) -> str: assert xpath("e + f") == ( "e/following-sibling::*[(self::f) and (position() = 1)]" ) - assert xpath("e ~ f") == ("e/following-sibling::f") + assert xpath("e ~ f") == ( + "e[position() = 1 or not(preceding-sibling::e[1])]/following-sibling::f" + ) assert xpath("e ~ f:nth-child(3)") == ( - "e/following-sibling::f[preceding-sibling::*[2] " + "e[position() = 1 or not(preceding-sibling::e[1])]" + "/following-sibling::f[preceding-sibling::*[2] " "and not(preceding-sibling::*[3])]" ) + assert xpath("e ~ f ~ g") == ( + "e[position() = 1 or not(preceding-sibling::e[1])]" + "/following-sibling::f[position() = 1 or not(preceding-sibling::f[1])]" + "/following-sibling::g" + ) + assert xpath("e.a ~ f") == ( + "e[@class and contains(@class, 'a') and contains(" + "concat(' ', normalize-space(@class), ' '), ' a ')]/following-sibling::f" + ) assert xpath("div#container p") == ("div[@id = 'container']/descendant::p") assert xpath("e:where(foo)") == "e[self::foo]" assert xpath("e:where(foo, bar)") == "e[(self::foo) or (self::bar)]" @@ -1697,6 +1709,21 @@ def pcss(main: str, *selectors: str, **kwargs: bool) -> list[str]: assert pcss("div + div") == ["foobar-div"] assert pcss("a ~ a") == ["tag-anchor", "nofollow-anchor"] assert pcss('a[rel="tag"] ~ a') == ["nofollow-anchor"] + assert pcss("li ~ li ~ li") == [ + "third-li", + "fourth-li", + "fifth-li", + "sixth-li", + "seventh-li", + ] + # From a context node with matching siblings before it + (fifth_li,) = typing.cast( + "list[etree._Element]", document.xpath("//*[@id = 'fifth-li']") + ) + items = typing.cast( + "list[etree._Element]", fifth_li.xpath(css_to_xpath("li ~ li")) + ) + assert [element.get("id") for element in items] == ["sixth-li", "seventh-li"] assert pcss("ol#first-ol li:last-child") == ["seventh-li"] assert pcss("ol#first-ol *:last-child") == ["li-div", "seventh-li"] assert pcss("#outer-div:first-child") == ["outer-div"] From e1737ade830cbbe8fec4f859e3d91f11daf33b4a Mon Sep 17 00:00:00 2001 From: Siraj saheb Date: Wed, 18 Nov 2026 00:24:11 +0530 Subject: [PATCH 2/3] only add the first ~ step test for prefixes that keep sibling lists contiguous --- cssselect/xpath.py | 49 ++++++++++++++++++++++++++++++++++++----- tests/test_cssselect.py | 29 ++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 6 deletions(-) diff --git a/cssselect/xpath.py b/cssselect/xpath.py index 3cd7271..dee74fd 100644 --- a/cssselect/xpath.py +++ b/cssselect/xpath.py @@ -60,6 +60,9 @@ def __init__( self.path = path self.element = element self.condition = condition + # A condition for the first step of `path`, kept aside until the + # axis that step is reached through is known: (offset, condition). + self.first_step_condition: tuple[int, str] | None = None def __str__(self) -> str: path = str(self.path) + str(self.element) @@ -96,6 +99,14 @@ def add_name_test(self) -> None: ) self.element = "*" + def apply_first_step_condition(self) -> Self: + """Add any pending condition to the first step of the path.""" + if self.first_step_condition is not None: + offset, condition = self.first_step_condition + self.path = f"{self.path[:offset]}[{condition}]{self.path[offset:]}" + self.first_step_condition = None + return self + def add_star_prefix(self) -> None: """ Append '*/' to the path to keep the context constrained @@ -132,6 +143,24 @@ def _or_conditions(conditions: list[str]) -> str: return " or ".join(f"({condition})" for condition in conditions) +# Prefixes whose axis gives, for each sibling list, either all of its +# elements, a contiguous run starting at the context node, or a single one, +# so that xpath_indirect_adjacent_combinator() can test the first step of +# a ~ chain with position(). +_SIBLING_SAFE_PREFIXES = frozenset( + { + "", + "descendant-or-self::", + "descendant::", + "child::", + "self::", + "parent::", + "following-sibling::", + "preceding-sibling::", + } +) + + #### Translation @@ -266,6 +295,8 @@ def selector_to_xpath( raise TypeError(f"Expected a parsed selector, got {selector!r}") xpath = self.xpath(tree) assert isinstance(xpath, self.xpathexpr_cls) # help debug a missing 'return' + if (prefix or "") in _SIBLING_SAFE_PREFIXES: + xpath.apply_first_step_condition() if translate_pseudo_elements and selector.pseudo_element: xpath = self.xpath_pseudo_element(xpath, selector.pseudo_element) return (prefix or "") + str(xpath) @@ -563,9 +594,15 @@ def xpath_indirect_adjacent_combinator( if not left.condition: # Only walk from the first left element among its siblings, or # from the first one of each context node (e.g. itself). - left.condition = ( - f"position() = 1 or not(preceding-sibling::{left.element}[1])" - ) + condition = f"position() = 1 or not(preceding-sibling::{left.element}[1])" + if left.path: + # Reached through a child, descendant or following-sibling + # step of this expression. + left.condition = condition + else: + # The first step: whether position() works depends on the + # prefix or :has() axis put in front of it later. + left.first_step_condition = (len(left.element), condition) return left.join("/following-sibling::", right) # The relative selector is kept in `condition` (instead of being folded @@ -574,11 +611,11 @@ def xpath_indirect_adjacent_combinator( def xpath_relation_descendant_combinator(self, right: XPathExpr) -> str: """right is a child, grand-child or further descendant of the element""" - return f"descendant::{right}" + return f"descendant::{right.apply_first_step_condition()}" def xpath_relation_child_combinator(self, right: XPathExpr) -> str: """right is an immediate child of the element""" - return f"./{right}" + return f"./{right.apply_first_step_condition()}" def xpath_relation_direct_adjacent_combinator(self, right: XPathExpr) -> str: """right is a sibling immediately after the element""" @@ -593,7 +630,7 @@ def xpath_relation_direct_adjacent_combinator(self, right: XPathExpr) -> str: def xpath_relation_indirect_adjacent_combinator(self, right: XPathExpr) -> str: """right is a sibling after the element, immediately or not""" - return f"following-sibling::{right}" + return f"following-sibling::{right.apply_first_step_condition()}" # Function: dispatch by function/pseudo-class name diff --git a/tests/test_cssselect.py b/tests/test_cssselect.py index 2ebf5a8..fb30da9 100644 --- a/tests/test_cssselect.py +++ b/tests/test_cssselect.py @@ -979,6 +979,16 @@ def xpath(css: str) -> str: "e[@class and contains(@class, 'a') and contains(" "concat(' ', normalize-space(@class), ' '), ' a ')]/following-sibling::f" ) + # The first step only gets the position() test when the prefix axis + # keeps sibling lists contiguous. + assert GenericTranslator().css_to_xpath("e ~ f ~ g", prefix="following::") == ( + "following::e/following-sibling::f" + "[position() = 1 or not(preceding-sibling::f[1])]/following-sibling::g" + ) + assert xpath("e:has(f ~ g)") == ( + "e[descendant::f[position() = 1 or not(preceding-sibling::f[1])]" + "/following-sibling::g]" + ) assert xpath("div#container p") == ("div[@id = 'container']/descendant::p") assert xpath("e:where(foo)") == "e[self::foo]" assert xpath("e:where(foo, bar)") == "e[(self::foo) or (self::bar)]" @@ -1883,6 +1893,25 @@ def select(css: str, translator: GenericTranslator) -> list[etree._Element]: element for element in all_elements if element not in matching ] + def test_select_indirect_adjacent_prefixes(self) -> None: + document = etree.fromstring( + "
  • " + "
  • " + ) + (context,) = typing.cast("list[etree._Element]", document.xpath("//x")) + + def select(prefix: str) -> list[str | None]: + xpath = GenericTranslator().css_to_xpath("li ~ li", prefix=prefix) + items = typing.cast("list[etree._Element]", context.xpath(xpath)) + return [element.get("id") for element in items] + + assert select("following::") == ["4"] + assert select("preceding::") == ["2", "b", "d", "3", "4"] + assert select("ancestor::") == ["d", "3", "4"] + assert select("ancestor-or-self::") == ["d", "3", "4"] + assert select("parent::") == ["d"] + assert select("descendant-or-self::") == [] + def test_select_long_selector_list(self) -> None: """A selector list is joined in a single ``or`` chain. From 421f191419af194bedffb33b191d371728b5bf72 Mon Sep 17 00:00:00 2001 From: Siraj saheb Date: Thu, 19 Nov 2026 14:08:31 +0530 Subject: [PATCH 3/3] make the first ~ step helpers private, skip the test on a self:: step --- cssselect/xpath.py | 38 +++++++++++++++++++++++--------------- tests/test_cssselect.py | 3 +++ 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/cssselect/xpath.py b/cssselect/xpath.py index 8d6ba51..1b131ec 100644 --- a/cssselect/xpath.py +++ b/cssselect/xpath.py @@ -62,7 +62,7 @@ def __init__( self.condition = condition # A condition for the first step of `path`, kept aside until the # axis that step is reached through is known: (offset, condition). - self.first_step_condition: tuple[int, str] | None = None + self._first_step_condition: tuple[int, str] | None = None def __str__(self) -> str: path = str(self.path) + str(self.element) @@ -99,12 +99,13 @@ def add_name_test(self) -> None: ) self.element = "*" - def apply_first_step_condition(self) -> Self: + def _apply_first_step_condition(self) -> Self: """Add any pending condition to the first step of the path.""" - if self.first_step_condition is not None: - offset, condition = self.first_step_condition + if self._first_step_condition is not None: + # pylint: disable-next=unpacking-non-sequence + offset, condition = self._first_step_condition self.path = f"{self.path[:offset]}[{condition}]{self.path[offset:]}" - self.first_step_condition = None + self._first_step_condition = None return self def add_star_prefix(self) -> None: @@ -296,7 +297,8 @@ def selector_to_xpath( xpath = self.xpath(tree) assert isinstance(xpath, self.xpathexpr_cls) # help debug a missing 'return' if (prefix or "") in _SIBLING_SAFE_PREFIXES: - xpath.apply_first_step_condition() + # pylint: disable-next=protected-access + xpath._apply_first_step_condition() if translate_pseudo_elements and selector.pseudo_element: xpath = self.xpath_pseudo_element(xpath, selector.pseudo_element) return (prefix or "") + str(xpath) @@ -593,14 +595,17 @@ def xpath_indirect_adjacent_combinator( # Only walk from the first left element among its siblings, or # from the first one of each context node (e.g. itself). condition = f"position() = 1 or not(preceding-sibling::{left.element}[1])" - if left.path: - # Reached through a child, descendant or following-sibling - # step of this expression. - left.condition = condition - else: + if not left.path: # The first step: whether position() works depends on the # prefix or :has() axis put in front of it later. - left.first_step_condition = (len(left.element), condition) + # pylint: disable-next=protected-access + left._first_step_condition = (len(left.element), condition) + elif not left.path.endswith("self::"): + # Reached through a child, descendant or following-sibling + # step of this expression. A self:: step (after +) gives at + # most one element per context node, so the test would not + # remove anything there. + left.condition = condition return left.join("/following-sibling::", right) # The relative selector is kept in `condition` (instead of being folded @@ -609,11 +614,13 @@ def xpath_indirect_adjacent_combinator( def xpath_relation_descendant_combinator(self, right: XPathExpr) -> str: """right is a child, grand-child or further descendant of the element""" - return f"descendant::{right.apply_first_step_condition()}" + # pylint: disable-next=protected-access + return f"descendant::{right._apply_first_step_condition()}" def xpath_relation_child_combinator(self, right: XPathExpr) -> str: """right is an immediate child of the element""" - return f"./{right.apply_first_step_condition()}" + # pylint: disable-next=protected-access + return f"./{right._apply_first_step_condition()}" def xpath_relation_direct_adjacent_combinator(self, right: XPathExpr) -> str: """right is a sibling immediately after the element""" @@ -628,7 +635,8 @@ def xpath_relation_direct_adjacent_combinator(self, right: XPathExpr) -> str: def xpath_relation_indirect_adjacent_combinator(self, right: XPathExpr) -> str: """right is a sibling after the element, immediately or not""" - return f"following-sibling::{right.apply_first_step_condition()}" + # pylint: disable-next=protected-access + return f"following-sibling::{right._apply_first_step_condition()}" # Function: dispatch by function/pseudo-class name diff --git a/tests/test_cssselect.py b/tests/test_cssselect.py index be5fc06..66276aa 100644 --- a/tests/test_cssselect.py +++ b/tests/test_cssselect.py @@ -972,6 +972,9 @@ def xpath(css: str) -> str: "/following-sibling::f[position() = 1 or not(preceding-sibling::f[1])]" "/following-sibling::g" ) + assert xpath("e + f ~ g") == ( + "e/following-sibling::*[1]/self::f/following-sibling::g" + ) assert xpath("e.a ~ f") == ( "e[@class and contains(@class, 'a') and contains(" "concat(' ', normalize-space(@class), ' '), ' a ')]/following-sibling::f"