Scrapy, a fast high-level web crawling & scraping framework for Python.
Support non-text responses in open_in_browser via Content-Type (#8067)
Adrian6073742a0c77
diff --git a/scrapy/utils/response.py b/scrapy/utils/response.pyindex 41bdac163..c9aa416f1 100644--- a/scrapy/utils/response.py+++ b/scrapy/utils/response.py@@ -5,6 +5,7 @@ scrapy.http.Response objectsfrom __future__ import annotations+import mimetypesimport osimport reimport tempfile@@ -64,7 +65,7 @@ _DOCTYPE_RE = re.compile(rb"\s*<!doctype[^<>]*>", re.IGNORECASE)def open_in_browser(- response: TextResponse,+ response: Response,_openfunc: Callable[[str], Any] = webbrowser.open,) -> Any:"""Open *response* in a local web browser, adjusting the `base tag`_ for@@ -105,7 +106,13 @@ def open_in_browser(elif isinstance(response, TextResponse):ext = ".txt"else:- raise TypeError(f"Unsupported response type: {response.__class__.__name__}")+ content_type = to_unicode(+ response.headers.get(b"Content-Type") or b"", encoding="latin-1"+ )+ mimetype = content_type.split(";")[0].strip().lower()+ ext = mimetypes.guess_extension(mimetype) or ""+ if not ext:+ raise TypeError(f"Unsupported response type: {response.__class__.__name__}")fd, fname = tempfile.mkstemp(ext)os.write(fd, body)os.close(fd)diff --git a/tests/test_utils_response.py b/tests/test_utils_response.pyindex 8269f0ad0..3324e9710 100644--- a/tests/test_utils_response.py+++ b/tests/test_utils_response.py@@ -39,7 +39,7 @@ def test_open_in_browser():resp = Response(url, body=body)with pytest.raises(TypeError):- open_in_browser(resp, _openfunc=browser_open) # type: ignore[arg-type]+ open_in_browser(resp, _openfunc=browser_open)def test_get_meta_refresh():@@ -337,4 +337,28 @@ def test_open_in_browser_text_response_uses_txt_extension():def test_open_in_browser_raises_for_unsupported_response_type():response = Response("http://www.example.com", body=b"binary")with pytest.raises(TypeError):- open_in_browser(response, _openfunc=lambda _: True) # type: ignore[arg-type]+ open_in_browser(response, _openfunc=lambda _: True)+++def test_open_in_browser_uses_content_type_for_extension():+ response = Response(+ "http://www.example.com/file.pdf",+ body=b"%PDF-1.4 fake pdf content",+ headers={"Content-Type": "application/pdf"},+ )++ def check(burl):+ assert burl.endswith(".pdf")+ return True++ assert open_in_browser(response, _openfunc=check)+++def test_open_in_browser_raises_for_unrecognized_content_type():+ response = Response(+ "http://www.example.com/file.bin",+ body=b"binary",+ headers={"Content-Type": "application/x-not-a-real-type"},+ )+ with pytest.raises(TypeError):+ open_in_browser(response, _openfunc=lambda _: True)