APIResponse
APIResponse 类表示由 api_request_context.get() 和类似方法返回的响应。
- 同步
- 异步
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
context = playwright.request.new_context()
response = context.get("https://example.com/user/repos")
assert response.ok
assert response.status == 200
assert response.headers["content-type"] == "application/json; charset=utf-8"
assert response.json()["name"] == "foobar"
assert response.body() == '{"status": "ok"}'
import asyncio
from playwright.async_api import async_playwright, Playwright
async def run(playwright: Playwright):
context = await playwright.request.new_context()
response = await context.get("https://example.com/user/repos")
assert response.ok
assert response.status == 200
assert response.headers["content-type"] == "application/json; charset=utf-8"
json_data = await response.json()
assert json_data["name"] == "foobar"
assert await response.body() == '{"status": "ok"}'
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
方法
body
添加于:v1.16返回带有响应体的缓冲区。
用法
api_response.body()
返回
dispose
添加于:v1.16处理此响应的主体。如果不调用此方法,则主体将保留在内存中,直到上下文关闭。
用法
api_response.dispose()
返回
json
添加于:v1.16返回响应体的 JSON 表示。
如果响应体无法通过 JSON.parse
解析,此方法将抛出错误。
用法
api_response.json()
返回
text
添加于:v1.16返回响应体的文本表示。
用法
api_response.text()
返回
属性
headers
添加于:v1.16一个包含与此响应相关联的所有响应 HTTP 头的对象。
用法
api_response.headers
返回
headers_array
添加于:v1.16一个包含与此响应相关联的所有响应 HTTP 头的数组。头名称不会转换为小写。具有多个条目的头,例如 Set-Cookie
,会在数组中多次出现。
用法
api_response.headers_array
返回
ok
添加于:v1.16包含一个布尔值,表示响应是否成功(状态码在 200-299 范围内)。
用法
api_response.ok
返回
status
添加于:v1.16包含响应的状态码(例如,成功时为 200)。
用法
api_response.status
返回
status_text
添加于:v1.16包含响应的状态文本(例如,成功时通常为 "OK")。
用法
api_response.status_text
返回
url
添加于:v1.16包含响应的 URL。
用法
api_response.url
返回