1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
|
"""
Selector tests for cssselect backend
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any
import cssselect
import pytest
from cssselect.parser import SelectorSyntaxError
from cssselect.xpath import ExpressionError
from packaging.version import Version
from parsel import Selector, css2xpath
from parsel.csstranslator import GenericTranslator, HTMLTranslator, TranslatorProtocol
HTMLBODY = """
<html>
<body>
<div>
<a id="name-anchor" name="foo"></a>
<a id="tag-anchor" rel="tag" href="http://localhost/foo">link</a>
<a id="nofollow-anchor" rel="nofollow" href="https://example.org"> link</a>
<p id="paragraph">
lorem ipsum text
<b id="p-b">hi</b> <em id="p-em">there</em>
<b id="p-b2">guy</b>
<input type="checkbox" id="checkbox-unchecked" />
<input type="checkbox" id="checkbox-disabled" disabled="" />
<input type="text" id="text-checked" checked="checked" />
<input type="hidden" />
<input type="hidden" disabled="disabled" />
<input type="checkbox" id="checkbox-checked" checked="checked" />
<input type="checkbox" id="checkbox-disabled-checked"
disabled="disabled" checked="checked" />
<fieldset id="fieldset" disabled="disabled">
<input type="checkbox" id="checkbox-fieldset-disabled" />
<input type="hidden" />
</fieldset>
</p>
<map name="dummymap">
<area shape="circle" coords="200,250,25" href="foo.html" id="area-href" />
<area shape="default" id="area-nohref" />
</map>
</div>
<div class="cool-footer" id="foobar-div" foobar="ab bc cde">
<span id="foobar-span">foo ter</span>
</div>
</body></html>
"""
class TestTranslatorBase(ABC):
@property
@abstractmethod
def tr_cls(self) -> type[TranslatorProtocol]:
raise NotImplementedError
def c2x(self, css: str) -> str:
return self.tr_cls().css_to_xpath(css)
@pytest.mark.parametrize(
("css", "xpath"),
[
("::attr(name)", "descendant-or-self::*/@name"),
("a::attr(href)", "descendant-or-self::a/@href"),
(
"a ::attr(img)",
"descendant-or-self::a/descendant-or-self::*/@img",
),
("a > ::attr(class)", "descendant-or-self::a/*/@class"),
],
)
def test_attr_function(self, css: str, xpath: str) -> None:
assert self.c2x(css) == xpath, css
@pytest.mark.parametrize(
("css", "exc"),
[
("::attr(12)", ExpressionError),
("::attr(34test)", ExpressionError),
("::attr(@href)", SelectorSyntaxError),
],
)
def test_attr_function_exception(self, css: str, exc: type[Exception]) -> None:
with pytest.raises(exc):
self.c2x(css)
@pytest.mark.parametrize(
("css", "xpath"),
[
("::text", "descendant-or-self::text()"),
("p::text", "descendant-or-self::p/text()"),
("p ::text", "descendant-or-self::p/descendant-or-self::text()"),
("#id::text", "descendant-or-self::*[@id = 'id']/text()"),
("p#id::text", "descendant-or-self::p[@id = 'id']/text()"),
(
"p#id ::text",
"descendant-or-self::p[@id = 'id']/descendant-or-self::text()",
),
("p#id > ::text", "descendant-or-self::p[@id = 'id']/*/text()"),
(
"p#id ~ ::text",
"descendant-or-self::p[@id = 'id']/following-sibling::*/text()",
),
("a[href]::text", "descendant-or-self::a[@href]/text()"),
(
"a[href] ::text",
"descendant-or-self::a[@href]/descendant-or-self::text()",
),
(
"p::text, a::text",
"descendant-or-self::p/text() | descendant-or-self::a/text()",
),
],
)
def test_text_pseudo_element(self, css: str, xpath: str) -> None:
assert self.c2x(css) == xpath, css
@pytest.mark.parametrize(
("css", "exc"),
[
("::attribute(12)", ExpressionError),
("::text()", ExpressionError),
("::attr(@href)", SelectorSyntaxError),
],
)
def test_pseudo_function_exception(self, css: str, exc: type[Exception]) -> None:
with pytest.raises(exc):
self.c2x(css)
@pytest.mark.parametrize(
("css", "exc"),
[
("::text-node", ExpressionError),
],
)
def test_unknown_pseudo_element(self, css: str, exc: type[Exception]) -> None:
with pytest.raises(exc):
self.c2x(css)
@pytest.mark.parametrize(
("css", "exc"),
[
(":text", ExpressionError),
(":attribute(name)", ExpressionError),
],
)
def test_unknown_pseudo_class(self, css: str, exc: type[Exception]) -> None:
with pytest.raises(exc):
self.c2x(css)
class TestHTMLTranslator(TestTranslatorBase):
tr_cls = HTMLTranslator
class TestGenericTranslator(TestTranslatorBase):
tr_cls = GenericTranslator
def test_css2xpath() -> None:
expected_xpath = (
"descendant-or-self::*[@class and contains("
"concat(' ', normalize-space(@class), ' '), ' some-class ')]"
)
assert css2xpath(".some-class") == expected_xpath
class TestCSSSelector:
sel = Selector(text=HTMLBODY)
def x(self, *a: Any, **kw: Any) -> list[str]:
return [v.strip() for v in self.sel.css(*a, **kw).extract() if v.strip()]
def test_selector_simple(self) -> None:
for x in self.sel.css("input"):
assert isinstance(x, self.sel.__class__), x
assert self.sel.css("input").extract() == [
x.extract() for x in self.sel.css("input")
]
def test_text_pseudo_element(self) -> None:
assert self.x("#p-b2") == ['<b id="p-b2">guy</b>']
assert self.x("#p-b2::text") == ["guy"]
assert self.x("#p-b2 ::text") == ["guy"]
assert self.x("#paragraph::text") == ["lorem ipsum text"]
assert self.x("#paragraph ::text") == ["lorem ipsum text", "hi", "there", "guy"]
assert self.x("p::text") == ["lorem ipsum text"]
assert self.x("p ::text") == ["lorem ipsum text", "hi", "there", "guy"]
def test_attribute_function(self) -> None:
assert self.x("#p-b2::attr(id)") == ["p-b2"]
assert self.x(".cool-footer::attr(class)") == ["cool-footer"]
assert self.x(".cool-footer ::attr(id)") == ["foobar-div", "foobar-span"]
assert self.x('map[name="dummymap"] ::attr(shape)') == ["circle", "default"]
def test_nested_selector(self) -> None:
assert self.sel.css("p").css("b::text").extract() == ["hi", "guy"]
assert self.sel.css("div").css("area:last-child").extract() == [
'<area shape="default" id="area-nohref">'
]
@pytest.mark.xfail(
Version(cssselect.__version__) < Version("1.2.0"),
reason="Support added in cssselect 1.2.0",
)
def test_pseudoclass_has(self) -> None:
assert self.x("p:has(b)::text") == ["lorem ipsum text"]
class TestCSSSelectorBytes(TestCSSSelector):
sel = Selector(body=bytes(HTMLBODY, encoding="utf-8"))
|