Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cssselect/xpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 29 additions & 2 deletions tests/test_cssselect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]"
Expand Down Expand Up @@ -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"]
Expand Down
Loading