Skip to content

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.toml
index 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.py
index 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_selector
def 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.py
index 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.text
kwargs.setdefault("base_url", get_base_url(response))
self.response = response
diff --git a/scrapy/utils/_deps_compat.py b/scrapy/utils/_deps_compat.py
index 519d83017..e96f0c417 100644
--- a/scrapy/utils/_deps_compat.py
+++ b/scrapy/utils/_deps_compat.py
@@ -2,7 +2,6 @@ import sys
from OpenSSL import __version__ as PYOPENSSL_VERSION_STRING
from packaging.version import Version
-from parsel import __version__ as PARSEL_VERSION_STRING
from twisted import version as TWISTED_VERSION
from 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/10232
TWISTED_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 immutable
PYOPENSSL_SET_CIPHER_LIST_TMP_CONN = PYOPENSSL_VERSION < Version("25.2.0")
diff --git a/tests/test_selector.py b/tests/test_selector.py
index aa43ce249..77799ad02 100644
--- a/tests/test_selector.py
+++ b/tests/test_selector.py
@@ -4,7 +4,6 @@ import pytest
from scrapy.http import HtmlResponse, JsonResponse, TextResponse, XmlResponse
from scrapy.selector import Selector
-from scrapy.utils._deps_compat import PARSEL_SUPPORTS_JMESPATH
class 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.ini
index 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.0
cryptography==41.0.5
- cssselect==0.9.1
+ cssselect==1.2.0
itemadapter==0.1.0
lxml==4.6.4
- parsel==1.5.0
+ parsel==1.8.1
platformdirs==2.0.0
pyOpenSSL==24.3.0
queuelib==1.6.1
@@ -328,10 +328,10 @@ deps =
brotlicffi==1.2.0.0
charset-normalizer==3.4.0
cryptography==44.0.2
- cssselect==0.9.1
+ cssselect==1.2.0
itemadapter==0.1.0
lxml==5.3.2
- parsel==1.5.0
+ parsel==1.8.1
pyOpenSSL==24.3.0
queuelib==1.6.1
service_identity==24.2.0