Development
Web 应用测试
使用 Playwright 与本地 Web 应用交互并对其进行测试的工具集。支持验证前端功能、调试 UI 行为、捕获浏览器截图以及查看浏览器日志。
要测试本地 Web 应用,请编写原生的 Python Playwright 脚本。
决策树:选择你的方式
User task → Is it static HTML?
├─ Yes → Read HTML file directly to identify selectors
│ ├─ Success → Write Playwright script using selectors
│ └─ Fails/Incomplete → Treat as dynamic (below)
│
└─ No (dynamic webapp) → Is the server already running?
├─ No → Run: python scripts/with_server.py --help
│ Then use the helper + write simplified Playwright script
│
└─ Yes → Reconnaissance-then-action:
1. Navigate and wait for networkidle
2. Take screenshot or inspect DOM
3. Identify selectors from rendered state
4. Execute actions with discovered selectors
示例:使用 with_server.py
单个服务器:
python scripts/with_server.py --server "npm run dev" --port 5173 -- python your_automation.py
多个服务器(例如后端 + 前端):
python scripts/with_server.py \
--server "cd backend && python server.py" --port 3000 \
--server "cd frontend && npm run dev" --port 5173 \
-- python your_automation.py
自动化脚本模板
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto('http://localhost:5173')
page.wait_for_load_state('networkidle')
# ... your automation logic
browser.close()
先侦察、后行动模式
-
检查渲染后的 DOM:
page.screenshot(path='/tmp/inspect.png', full_page=True) content = page.content() page.locator('button').all() -
从检查结果中识别选择器
-
使用发现的选择器执行动作
常见陷阱
❌ 不要在动态应用上未等待 networkidle 就检查 DOM
✅ 务必在检查前等待 page.wait_for_load_state('networkidle')
最佳实践
- 将捆绑的脚本当作黑盒使用
- 同步脚本使用
sync_playwright() - 完成后务必关闭浏览器
- 使用有描述性的选择器:
text=、role=、CSS 选择器或 ID - 添加适当的等待:
page.wait_for_selector()或page.wait_for_timeout()