Scrapy, a fast high-level web crawling & scraping framework for Python.
Reuse a UTF-8 str body as TextResponse.text (#8220)
Adrian71172304618e
diff --git a/scrapy/http/response/text.py b/scrapy/http/response/text.pyindex f6a6c043e..411239800 100644--- a/scrapy/http/response/text.py+++ b/scrapy/http/response/text.py@@ -69,6 +69,13 @@ class TextResponse(Response):f"{type(self).__name__} has no encoding")self._body = body.encode(self._encoding)+ # Keep body as text only if decoding _body gives it back+ # unchanged. html_to_unicode() may resolve the encoding to+ # another codec (e.g. latin-1 to cp1252) and strips a BOM.+ if resolve_encoding(self._encoding) == "utf-8" and not body.startswith(+ "\ufeff"+ ):+ self._cached_ubody = bodyelse:super()._set_body(body)diff --git a/tests/test_http_response_text.py b/tests/test_http_response_text.pyindex 5745dfa0c..eb9283fe1 100644--- a/tests/test_http_response_text.py+++ b/tests/test_http_response_text.py@@ -87,6 +87,21 @@ class TestTextResponse(TestResponseBase):assert isinstance(r1.text, str)assert r1.text == unicode_string+ @pytest.mark.parametrize(+ ("body", "encoding", "text", "reused"),+ [+ ("\xa3\U0001f600", "utf8", "\xa3\U0001f600", True),+ ("\ufeffWORD", "utf-8", "WORD", False),+ ("\x80", "latin-1", "\u20ac", False),+ ],+ )+ def test_str_body_text(+ self, body: str, encoding: str, text: str, reused: bool+ ) -> None:+ r = self.response_class("http://www.example.com", body=body, encoding=encoding)+ assert r.text == text+ assert (r.text is body) is reused+def test_encoding(self):r1 = self.response_class("http://www.example.com",