前言
每个Playwright浏览器上下文都有与其关联的APIRequestContext实例,该实例与浏览器上下文共享cookie存储,可以通过browser_context.request或page.request访问。也可以通过调用api_request.new_context()手动创建一个新的APIRequest上下文实例。
通过浏览器发请求
可以通过browser_context.request或page.request发送接口请求,该实例与浏览器上下文共享cookie存储。
page.request() 发送请求
也可以通过page.request() 发送接口请求
代码语言:javascript复制from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto('https://www.cnblogs.com/yoyoketang/')
# 发post请求
resp = page.request.post(
url="http://www.example.com/",
data={"user": "test", "email": "123@qq.com"}
)
print(resp.status)
print(resp.headers)
print(resp.body())
APIRequestContext
不打开浏览器的情况下,直接发接口请求也是可以的
代码语言:javascript复制from playwright.sync_api import sync_playwright
with sync_playwright() as p:
context = p.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"}'