Scrapy, a fast high-level web crawling & scraping framework for Python.
Avoid decoding response bodies for html/xml selectors when possible (#8195)
Adrian506555bf9d79
diff --git a/pyproject.toml b/pyproject.tomlindex d7cca1bfd..e538b74ad 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -11,13 +11,13 @@ dependencies = ["aiohttp>=3.13.3","charset-normalizer>=3.4.0","cryptography>=41.0.5",- "cssselect>=0.9.1",+ "cssselect>=1.2.0","defusedxml>=0.7.1","itemadapter>=0.1.0","itemloaders>=1.0.1","lxml>=4.6.4","packaging",- "parsel>=1.5.0",+ "parsel>=1.8.1","platformdirs>=2.0.0","protego>=0.1.15","pyOpenSSL>=24.3.0",diff --git a/scrapy/http/response/text.py b/scrapy/http/response/text.pyindex c4c48db1c..f6a6c043e 100644--- a/scrapy/http/response/text.py+++ b/scrapy/http/response/text.py@@ -167,10 +167,6 @@ class TextResponse(Response):return self._cached_selectordef jmespath(self, query: str, **kwargs: Any) -> SelectorList:- if not hasattr(self.selector, "jmespath"):- raise AttributeError(- "Please install parsel >= 1.8.1 to get jmespath support"- )return cast("SelectorList", self.selector.jmespath(query, **kwargs))def xpath(self, query: str, **kwargs: Any) -> SelectorList:diff --git a/scrapy/selector/unified.py b/scrapy/selector/unified.pyindex 1c90c75cb..5e8242ea6 100644--- a/scrapy/selector/unified.py+++ b/scrapy/selector/unified.py@@ -100,7 +100,20 @@ class Selector(_ParselSelector, object_ref):response = _response_from_text(text, type)if response is not None:- text = response.text+ # parsel only treats bytes and text equivalently for "html" and+ # "xml", and treats an empty body as absent, unlike empty text.+ if type in ("html", "xml") and response.body:+ encoding = response.encoding+ # None means the encoding was declared, not inferred from+ # the body, so the body hasn't been decoded as a side effect.+ if response._cached_ubody is None:+ kwargs["body"] = response.body+ kwargs["encoding"] = encoding+ text = None+ else:+ text = response.text+ else:+ text = response.textkwargs.setdefault("base_url", get_base_url(response))self.response = responsediff --git a/scrapy/utils/_deps_compat.py b/scrapy/utils/_deps_compat.pyindex 519d83017..e96f0c417 100644--- a/scrapy/utils/_deps_compat.py+++ b/scrapy/utils/_deps_compat.py@@ -2,7 +2,6 @@ import sysfrom OpenSSL import __version__ as PYOPENSSL_VERSION_STRINGfrom packaging.version import Version-from parsel import __version__ as PARSEL_VERSION_STRINGfrom twisted import version as TWISTED_VERSIONfrom twisted.python.versions import Version as TxVersion@@ -17,10 +16,6 @@ TWISTED_TLS_NEW_IMPL = TWISTED_VERSION >= TxVersion("twisted", 26, 4, 0)# lowerMaximumSecurityTo off-by-1, https://github.com/twisted/twisted/issues/10232TWISTED_TLS_LIMITS_OFFBY1 = TWISTED_VERSION < TxVersion("twisted", 26, 4, 0)-PARSEL_VERSION = Version(PARSEL_VERSION_STRING)-# Selector.jmespath() support-PARSEL_SUPPORTS_JMESPATH = PARSEL_VERSION >= Version("1.8.0")-PYOPENSSL_VERSION = Version(PYOPENSSL_VERSION_STRING)# SSL.Context.set_cipher_list() creates a temporary connection, making the context immutablePYOPENSSL_SET_CIPHER_LIST_TMP_CONN = PYOPENSSL_VERSION < Version("25.2.0")diff --git a/tests/test_selector.py b/tests/test_selector.pyindex aa43ce249..77799ad02 100644--- a/tests/test_selector.py+++ b/tests/test_selector.py@@ -4,7 +4,6 @@ import pytestfrom scrapy.http import HtmlResponse, JsonResponse, TextResponse, XmlResponsefrom scrapy.selector import Selector-from scrapy.utils._deps_compat import PARSEL_SUPPORTS_JMESPATHclass TestSelector:@@ -56,9 +55,6 @@ class TestSelector:'<div><img src="a.jpg"><p>Hello</p></div>']- @pytest.mark.skipif(- not PARSEL_SUPPORTS_JMESPATH, reason="parsel < 1.8 doesn't support json"- )def test_flavor_detection_json(self) -> None:response = JsonResponse("http://example.com", body=b'{"a": "b"}', encoding="utf-8"@@ -66,9 +62,6 @@ class TestSelector:assert Selector(response).type == "json"assert response.jmespath("a").get() == "b"- @pytest.mark.skipif(- not PARSEL_SUPPORTS_JMESPATH, reason="parsel < 1.8 doesn't support json"- )def test_flavor_detection_json_with_html_body(self) -> None:body = b"<div><p>Hello</p></div>"response = JsonResponse("http://example.com", body=body, encoding="utf-8")@@ -128,9 +121,6 @@ class TestSelector:Selector(TextResponse(url="http://example.com", body=b""), text="")- not PARSEL_SUPPORTS_JMESPATH, reason="parsel < 1.8 doesn't support jmespath"-)class TestJMESPath:def test_json_has_html(self) -> None:"""Sometimes the information is returned in a json wrapper"""@@ -265,15 +255,3 @@ class TestJMESPath:assert resp.xpath("//div/content").jmespath("user[*].age.to_string(@)").re(r"(\d+)") == ["18", "32", "22", "25"]--[email protected](PARSEL_SUPPORTS_JMESPATH, reason="parsel >= 1.8 supports jmespath")-def test_jmespath_not_available() -> None:- body = """- {- "website": {"name": "Example"}- }- """- resp = TextResponse(url="http://example.com", body=body, encoding="utf-8")- with pytest.raises(AttributeError):- resp.jmespath("website.name").get()diff --git a/tox.ini b/tox.iniindex 4344b9136..409d2c571 100644--- a/tox.ini+++ b/tox.ini@@ -147,10 +147,10 @@ deps =brotlicffi==1.2.0.0; implementation_name == "pypy"charset-normalizer==3.4.0cryptography==41.0.5- cssselect==0.9.1+ cssselect==1.2.0itemadapter==0.1.0lxml==4.6.4- parsel==1.5.0+ parsel==1.8.1platformdirs==2.0.0pyOpenSSL==24.3.0queuelib==1.6.1@@ -328,10 +328,10 @@ deps =brotlicffi==1.2.0.0charset-normalizer==3.4.0cryptography==44.0.2- cssselect==0.9.1+ cssselect==1.2.0itemadapter==0.1.0lxml==5.3.2- parsel==1.5.0+ parsel==1.8.1pyOpenSSL==24.3.0queuelib==1.6.1service_identity==24.2.0