APIResponse
APIResponse 表示 api_request_context.get(url, **kwargs) 及类似方法返回的响应对象。
- Sync
- Async
from playwright.sync_api import sync_playwright
with sync_playwright() as playwright:
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"
assert response.json()["name"] == "foobar"
assert await response.body() == '{"status": "ok"}'
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
- api_response.body()
- api_response.dispose()
- api_response.headers
- api_response.headers_array
- api_response.json()
- api_response.ok
- api_response.status
- api_response.status_text
- api_response.text()
- api_response.url
api_response.body()
Added in: v1.16返回响应正文的二进制缓冲区。
api_response.dispose()
Added in: v1.16释放该响应的正文内容。若不调用,此正文会一直留在内存中直至上下文关闭。
api_response.headers
Added in: v1.16返回与此响应相关的全部 HTTP 响应头字典。
api_response.headers_array
Added in: v1.16以数组形式返回与响应关联的 HTTP 请求头。名称保持原始大小写。多值头(如 Set-Cookie)会出现多次。
api_response.json()
Added in: v1.16- 返回值: <Serializable>#
返回响应正文的 JSON 表示。
若响应正文无法通过 JSON.parse 解析会抛出异常。
api_response.ok
Added in: v1.16布尔值,表明响应是否成功(状态码处于 200-299)。
api_response.status
Added in: v1.16响应的状态码(例如 200)。
api_response.status_text
Added in: v1.16响应状态码对应的文本描述(如成功时通常为 "OK")。
api_response.text()
Added in: v1.16返回响应正文的文本形式。
api_response.url
Added in: v1.16响应的 URL。