Skip to content

Commit 8950c29

Browse files
committed
Infer response type from the body
1 parent 14db86a commit 8950c29

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,27 @@ does not match the running Browser. If you prefer the `User-Agent` sent by
133133
default by the specific browser you're using, set the Scrapy user agent to `None`.
134134

135135

136+
### About the response body and type
137+
138+
The body of a Playwright response is the serialized DOM of the page, as rendered by the
139+
browser. Browsers wrap non-HTML content in HTML tags of their own: a JSON document is
140+
usually displayed inside a `<pre>` tag, sometimes along with viewer-specific markup.
141+
Because of that, responses are HTML (`scrapy.http.HtmlResponse`) regardless of the
142+
`Content-Type` header reported by the server, and the body of a request to a JSON
143+
endpoint cannot be parsed directly with `Response.json` or `Response.jmespath`. Extract
144+
the text node first, e.g.:
145+
146+
```python
147+
import json
148+
149+
def parse(self, response, **kwargs):
150+
data = json.loads(response.css("pre::text").get())
151+
```
152+
153+
This does not apply to [downloads](#playwright_suggested_filename), which keep the bytes
154+
and the type of the downloaded file.
155+
156+
136157
## Windows support
137158

138159
Windows support is possible by running Playwright in a `ProactorEventLoop` in a separate thread.

scrapy_playwright/handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ async def _download_request_with_page(
580580
)
581581

582582
body, encoding = _encode_body(headers=headers, text=body_str)
583-
respcls = responsetypes.from_args(headers=headers, url=page.url, body=body)
583+
respcls = responsetypes.from_args(body=body)
584584
return respcls(
585585
url=page.url,
586586
status=response.status if response is not None else 200,

0 commit comments

Comments
 (0)