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
57 changes: 54 additions & 3 deletions cssselect/xpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -96,6 +99,15 @@ 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:
# 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
return self

def add_star_prefix(self) -> None:
"""
Append '*/' to the path to keep the context constrained
Expand Down Expand Up @@ -132,6 +144,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


Expand Down Expand Up @@ -266,6 +296,9 @@ 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:
# 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)
Expand Down Expand Up @@ -558,6 +591,21 @@ 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).
condition = f"position() = 1 or not(preceding-sibling::{left.element}[1])"
if not left.path:
# The first step: whether position() works depends on the
# prefix or :has() axis put in front of it later.
# 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
Expand All @@ -566,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}"
# 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}"
# 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"""
Expand All @@ -585,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}"
# pylint: disable-next=protected-access
return f"following-sibling::{right._apply_first_step_condition()}"

# Function: dispatch by function/pseudo-class name

Expand Down
63 changes: 61 additions & 2 deletions tests/test_cssselect.py
Original file line number Diff line number Diff line change
Expand Up @@ -959,11 +959,36 @@ def xpath(css: str) -> str:
assert xpath("e *") == ("e/descendant-or-self::*/*")
assert xpath("e > f") == ("e/f")
assert xpath("e + f") == ("e/following-sibling::*[1]/self::f")
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 + 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"
)
# 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)]"
Expand Down Expand Up @@ -1692,6 +1717,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 Expand Up @@ -1851,6 +1891,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(
"<r><li id='1'/><li id='2'><u><li id='a'/><li id='b'><x id='c'/></li>"
"<li id='d'/></u></li><li id='3'/><li id='4'/></r>"
)
(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.

Expand Down
Loading