Python Playwright 安装
官方文档
https://playwright.net.cn/python/docs/actionability1,Pip 安装
# 安装 Playwright 库 pip install playwright # 自动安装浏览器二进制文件(Chromium/Firefox/WebKit) playwright installplaywright install 默认安装全部 3 种浏览器,若只需单个,可指定参数:
# 仅安装Chromium(Chrome内核) playwright install chromium # 仅安装Firefox playwright install firefox # 仅安装WebKit(Safari内核) playwright install webkit2,安装 Playwright Pytest
Playwright 建议使用官方的 Playwright Pytest 插件来编写端到端测试。它开箱即用地提供了上下文隔离,并支持在多种浏览器配置上运行。
安装 Pytest 插件
pip install pytest-playwright3,添加示例测试
在当前工作目录或子目录中创建一个遵循test_前缀约定的文件,例如test_example.py,并将以下代码放入其中。请确保您的测试名称也遵循test_前缀约定。
pycharm测试配置参数
# 正确的 pytest + Playwright 测试用例 from playwright.sync_api import sync_playwright def test_baidu(): # 1. 启动 Playwright with sync_playwright() as p: # 2. 启动浏览器(headed=显示界面,无头模式默认True) browser = p.chromium.launch(headless=False) # 3. 创建新页面(核心实例:小写 page) page = browser.new_page() # 4. 访问百度(正确网址) page.goto("https://www.baidu.com") # 5. 打印页面标题 print("页面标题:", page.title()) # 6. 等待5秒 page.wait_for_timeout(5000) # 7. 关闭浏览器 browser.close()D:\py\python.exe "D:/pychamr/PyCharm 2024.1.3/plugins/python/helpers/pycharm/_jb_pytest_runner.py" --path D:\pycharmdome\pythonProject15\test_run.py -- -v --headed Testing started at 下午7:42 ... Launching pytest with arguments -v --headed D:\pycharmdome\pythonProject15\test_run.py --no-header --no-summary -q in D:\pycharmdome\pythonProject15 ============================= test session starts ============================= collecting ... collected 1 item test_run.py::test_case PASSED [100%]页面标题: 百度一下,你就知道 ======================= 1 passed, 2 warnings in 10.24s ======================== 进程已结束,退出代码为 0