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"]