diff --git a/cssselect/xpath.py b/cssselect/xpath.py index 11eed54..05f26b6 100644 --- a/cssselect/xpath.py +++ b/cssselect/xpath.py @@ -444,7 +444,7 @@ def xpath_attrib(self, selector: Attrib) -> XPathExpr: else: value = selector.value.value attribute = None - if selector.namespace == "*" and selector.operator not in ("exists", "!="): + if selector.namespace == "*" and selector.operator != "exists": # String functions convert a node-set to its first node's value. # Apply the operator to each attribute before testing existence. attribute = attrib @@ -454,6 +454,18 @@ def xpath_attrib(self, selector: Attrib) -> XPathExpr: # case-insensitive match as, and all XPath 1.0 can express. attrib = f"translate({attrib}, {self.xpath_literal(ascii_uppercase)}, {self.xpath_literal(ascii_lowercase)})" value = ascii_lower(value) + if attribute is not None and selector.operator == "!=": + # [*|foo!=bar] is :not([*|foo=bar]): no attribute may be equal, + # not just one of them different. An empty value still requires + # the attribute to exist, like [foo!='']. + assert value is not None + condition = self.xpath_attrib_equals( + self.xpathexpr_cls(), attrib, value + ).condition + condition = f"not({attribute}[{condition}])" + if not value: + condition = f"{attribute} and {condition}" + return self.xpath(selector.selector).add_condition(condition) if attribute is not None: condition = method(self.xpathexpr_cls(), attrib, value).condition return self.xpath(selector.selector).add_condition( diff --git a/tests/test_cssselect.py b/tests/test_cssselect.py index e98b5cb..2b4bfa9 100644 --- a/tests/test_cssselect.py +++ b/tests/test_cssselect.py @@ -1920,6 +1920,29 @@ def test_select_with_wildcard_attribute_combinations(self) -> None: xpath = GenericTranslator().css_to_xpath(selector) assert document.xpath(xpath + "/@id") == expected + def test_select_with_wildcard_attribute_different(self) -> None: + # [*|label!=v] is :not([*|label=v]) (except for an empty value), + # whichever attribute comes first. + document = etree.XML( + '' + '' + '' + '' + '' + '' + ) + cases = [ + ("item[*|label!=bar]", ["second", "other", "empty", "missing"]), + ("item[*|label!=bar s]", ["second", "other", "empty", "missing"]), + ("item[*|label!=bar i]", ["other", "empty", "missing"]), + ('item[*|label!=""]', ["first", "second", "other"]), + ('item[*|label!="" i]', ["first", "second", "other"]), + ] + for selector, expected in cases: + with self.subTest(selector=selector): + xpath = GenericTranslator().css_to_xpath(selector) + assert document.xpath(xpath + "/@id") == expected + def test_select_with_default_namespace(self) -> None: # A bare "f" translates to an unprefixed XPath node test, which # only matches elements in *no* namespace, so it cannot see