Playwright设置base_url的三种方式
方式一:playwright创建new_context()
- 在new_context(base_url=‘’)中指定base_url
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(base_url="http://localhost:8080")
示例代码:
import json
from playwright.sync_api import Playwright, sync_playwright
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(base_url="http://localhost:8080")
page = context.new_page()
page.goto("/login")
page.get_by_role("textbox", name="用户名").click()
page.get_by_role("textbox", name="用户名").fill("admin")
page.get_by_role("textbox", name="密码").click()
page.get_by_role("textbox", name="密码").fill("admin123")
page.get_by_role("button", name="登录").click()
# 等待页面跳转,作为登录成功的标准
page.wait_for_url(url='http://localhost:8080/index')
# page.pause()
# 保存storage state 到指定的文件
# 使用该方法前,需要确认网站cookie的失效时间
storage = context.storage_state(path='../../auth/ry_auto.json')
print(storage)
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
方式二:使用插件pytest-playwright
pip install pytest-playwright
- 在
pytest.ini
配置文件中,使用addopts
属性在命令行中添加参数--base-url http://localhost:8080
pytest.ini
配置文件如下:
[pytest]
addopts = -s --base-url http://localhost:8080
方式三:使用插件pytest-base-url
- 该插件在
pytest.ini
配置文件中,添加了一个行属性,base_url
。
pip install pytest-base-url
pytest.ini
配置文件如下:
[pytest]
base_url = http://localhost:8080