python+playwright 学习-77 playwright 发送接口请求APIRequestContext
前言
每个Playwright浏览器上下文都有与其关联的APIRequestContext实例,该实例与浏览器上下文共享cookie存储,可以通过browser_context.request或page.request访问。也可以通过调用api_request.new_context()手动创建一个新的APIRequest上下文实例。
通过浏览器发请求
可以通过browser_context.request或page.request发送接口请求,该实例与浏览器上下文共享cookie存储。
from playwright.sync_api import sync_playwright, expect
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/
REPO = "test-repo-1"
USER = "github-username"
API_TOKEN = "xx1122"
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context(base_url="https://api.github.com")
# context 上下文创建 request 请求对象
api_request_context = context.request
page = context.new_page()
# 访问浏览器页面
page.goto('https://api.github.com')
# Create a repository.
response = api_request_context.post(
"/user/repos",
headers={
"Accept": "application/vnd.github.v3+json",
# Add GitHub personal access token.
"Authorization": f"token {API_TOKEN}",
},
data={"name": REPO},
)
assert response.ok
assert response.json()["name"] == REPO
# Delete a repository.
response = api_request_context.delete(
f"/repos/{USER}/{REPO}",
headers={
"Accept": "application/vnd.github.v3+json",
# Add GitHub personal access token.
"Authorization": f"token {API_TOKEN}",
},
)
assert response.ok
assert response.body() == '{"status": "ok"}'
page.request() 发送请求
也可以通过page.request() 发送接口请求
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
不打开浏览器的情况下,直接发接口请求也是可以的
from playwright.sync_api import sync_playwright
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/
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"}'