Python Playwright UI自动化测试环境配置完全指南
作者:Clear Breeze
Playwright 是微软出品的强大跨浏览器自动化测试工具,相比 Selenium 具有更快的执行速度、更好的稳定性、更现代的API设计。本文详细介绍如何在 Windows 环境下配置 Playwright 测试环境,并在 Trae IDE 中进行开发。
🛠️ 一、环境准备
1.1 系统要求
要求 | 推荐版本 |
|---|---|
操作系统 | Windows 10/11 或 Windows Server 2019+ |
Python | Python 3.8+ |
内存 | 8GB+ |
硬盘 | 10GB+ 可用空间 |
1.2 安装 Python
推荐使用 Python 3.9 或 3.10/3.11 版本:
# 检查Python版本 python --version # 如果未安装,推荐使用 Python 3.11 # 下载地址:https://www.python.org/downloads/
安装时注意:
- ✅ 勾选 "Add Python to PATH"
- ✅ 勾选 "Install pip"
- ✅ 推荐使用自定义安装,选择 "Python for all users"
📦 二、Playwright 依赖安装
2.1 创建项目结构
# 创建项目目录 mkdir auto_ui cd auto_ui # 创建虚拟环境(推荐) python -m venv venv # 激活虚拟环境 .\venv\Scripts\activate # 如果遇到执行策略问题 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
2.2 安装 Playwright
# 安装Playwright(会包含测试框架) pip install playwright pytest-playwright # 或者分步安装 pip install playwright pip install pytest pip install pytest-playwright # 安装AI集成所需的包(可选) pip install openai anthropic pip install python-dotenv
2.3 创建依赖文件
# requirements.txt playwright==1.58.0 pytest==8.0.0 pytest-playwright==0.4.4 pytest-html==4.1.1 allure-pytest==2.13.2 # YAML配置支持 PyYAML==6.0.1 # AI集成(可选) openai==1.12.0 anthropic==0.18.0 python-dotenv==1.0.1 # 日志和时间 python-dateutil==2.8.2
安装命令:
pip install -r requirements.txt
🌐 三、Playwright 浏览器安装
3.1 官方源安装(推荐)
# 安装Chromium浏览器 python -m playwright install chromium # 安装所有浏览器 python -m playwright install # 指定安装位置 python -m playwright install chromium --with-deps
注意:官方源下载可能需要5-15分钟,耐心等待。
3.2 使用系统Chrome
如果系统已安装Chrome,可以直接使用,无需下载:
# 检查系统Chrome路径 Test-Path "C:\Program Files\Google\Chrome\Application\chrome.exe"
在代码中启用系统Chrome:
# conftest.py
@pytest.fixture(scope="function")
def browser_context(browser):
context = browser.new_context(
no_viewport=True,
channel='chrome', # 使用系统Chrome
)
context.set_default_timeout(TIMEOUT)
yield context
context.close()3.3 国内镜像安装
清华镜像(已停止维护):
# 已不推荐使用
推荐方案:使用代理或下载官方版本。
3.4 验证安装
# 检查版本
python -m playwright --version
# 检查浏览器路径
python -m playwright show-browser-path
# 验证浏览器可用
python -c "from playwright.sync_api import sync_playwright; p = sync_playwright().start(); b = p.chromium.launch(); print('Chromium 可用 ✓'); b.close(); p.stop()"💻 四、Trae IDE 配置
4.1 Trae IDE 简介
Trae IDE 是基于 VS Code 的现代化 Python IDE,内置 AI 辅助功能,非常适合自动化测试开发。
下载地址:https://trae.ai/
4.2 项目导入
# 方式1:直接打开项目目录 # 菜单 File → Open Folder → 选择项目目录 # 方式2:命令行打开 code .
4.3 Python 解释器配置
1. 按 Ctrl+Shift+P 打开命令面板 2. 输入 "Python: Select Interpreter" 3. 选择项目虚拟环境中的Python 路径类似:项目路径\venv\Scripts\python.exe
4.4 必装插件
在 Trae IDE 扩展市场中安装:
插件名称 | 用途 |
|---|---|
Python | Python语言支持 |
Pylance | Python类型检查和智能提示 |
Ruff | Python代码格式化 |
Playwright | Playwright测试支持 |
Error Lens | 错误即时显示 |
4.5 设置自动测试
在 .vscode/settings.json 中配置:
{
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": [
"tests",
"-v",
"--tb=short"
],
"python.testing.unittestEnabled": false,
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true
}
}4.6 Trae AI 配置(可选)
如果使用 Trae 的 AI 功能:
1. 登录 Trae 账号 2. 设置 → AI → 选择模型 3. 可选模型: - Claude - GPT-4 - Gemini
🤖 五、AI 模型配置
5.1 配置AI服务
创建 .env 文件(添加到 .gitignore):
# OpenAI配置 OPENAI_API_KEY=sk-xxxxx OPENAI_API_BASE=https://api.openai.com/v1 # Anthropic配置(Claude) ANTHROPIC_API_KEY=sk-ant-xxxxx # 国内代理(如果需要) HTTP_PROXY=http://127.0.0.1:7890 HTTPS_PROXY=http://127.0.0.1:7890
5.2 AI辅助开发示例
场景1:让AI帮你写测试用例
# 提示词示例 """ 请帮我为这个登录页面写测试用例: 页面包含: - 用户名输入框 - 密码输入框 - 登录按钮 - 记住登录复选框 请生成: 1. Page Object类结构 2. 正常登录测试 3. 错误密码测试 4. 空用户名测试 """
场景2:让AI帮你分析错误
# 当测试失败时,让AI分析 """ 测试失败了,日志显示: - 错误:ElementClickInterceptedException - 截图已保存 页面结构可能发生了变化,请分析: 1. 可能的原因? 2. 如何修改选择器? 3. 如何添加重试逻辑? """
5.3 代码示例:AI日志分析
# utils/ai_logger.py
from openai import OpenAI
import os
class AILogger:
def __init__(self):
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def analyze_error(self, error_info: str, screenshot_path: str = None) -> str:
"""使用AI分析测试错误"""
prompt = f"""
测试自动化执行遇到错误:
错误信息:
{error_info}
请分析:
1. 最可能的原因?
2. 解决方案建议?
3. 如何避免类似问题?
"""
response = self.client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content📁 六、项目配置结构
6.1 目录结构
auto_ui/ ├── config/ # 配置目录 │ ├── __init__.py │ ├── settings.py # Python配置 │ └── config.yaml # YAML配置 ├── pages/ # 页面对象 │ ├── __init__.py │ ├── base_page.py │ └── login_page.py ├── tests/ # 测试用例 │ ├── __init__.py │ └── test_*.py ├── utils/ # 工具函数 │ ├── __init__.py │ ├── logger.py │ └── decorators.py ├── conftest.py # pytest配置 ├── pytest.ini # pytest设置 └── requirements.txt # 依赖清单
6.2 配置文件示例
# config/config.yaml base_url: "https://test.example.com" timeout: 30000 headless: false browser: "chromium" wait_timeouts: short: 2000 medium: 3000 long: 5000 page_load: 30000 reports: output_dir: "reports" logs_dir: "logs" screenshots_dir: "screenshots" test_user: username: "test@example.com" password: "password123"
# config/settings.py
import os
import yaml
from pathlib import Path
BASE_DIR = Path(__file__).parent.parent
# 加载YAML配置
CONFIG_FILE = BASE_DIR / "config" / "config.yaml"
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
_config = yaml.safe_load(f)
# 配置项
BASE_URL = _config.get("base_url")
TIMEOUT = _config.get("timeout", 30000)
HEADLESS = _config.get("headless", False)
BROWSER = _config.get("browser", "chromium")6.3 pytest配置
# pytest.ini
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts =
-v
--tb=short
--strict-markers
--html=reports/report.html
--self-contained-html
markers =
ui: UI自动化测试
smoke: 冒烟测试
regression: 回归测试6.4 conftest.py配置
# conftest.py
import pytest
from playwright.sync_api import sync_playwright
from config.settings import *
@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args):
return {
**browser_type_launch_args,
"headless": HEADLESS,
"slow_mo": SLOW_MO,
"args": ["--start-maximized"],
}
@pytest.fixture(scope="function")
def browser_context(browser):
context = browser.new_context(no_viewport=True)
context.set_default_timeout(TIMEOUT)
yield context
context.close()
@pytest.fixture(scope="function")
def page(browser_context):
page = browser_context.new_page()
page.set_default_timeout(TIMEOUT)
# 窗口最大化
page.evaluate("""
window.moveTo(0, 0);
window.resizeTo(window.screen.availWidth, window.screen.availHeight);
""")
yield page
page.close()🔧 七、常见问题解决
7.1 安装问题
Q1:下载浏览器太慢
# 方案1:使用代理 $env:HTTPS_PROXY = "http://127.0.0.1:7890" python -m playwright install chromium # 方案2:使用系统Chrome(跳过下载) # 修改conftest.py,添加 channel='chrome'
Q2:安装失败,权限错误
# 方案1:以管理员身份运行 # 右键PowerShell → 以管理员身份运行 # 方案2:清理后重试 Remove-Item -Recurse -Force "$env:LOCALAPPDATA\ms-playwright" python -m playwright install chromium
Q3:浏览器无法启动
# 检查依赖 python -m playwright install-deps # 或者手动安装Visual C++ Redistributable
7.2 运行问题
Q4:测试超时
# 增加超时时间 page.set_default_timeout(60000) # 60秒 # 或在配置中修改 TIMEOUT = 60000
Q5:元素找不到
# 添加等待
page.wait_for_load_state("networkidle")
# 或显式等待
page.wait_for_selector(".element", timeout=5000)Q6:截图保存失败
# 确保目录存在
import os
os.makedirs("screenshots", exist_ok=True)
# 保存截图
page.screenshot(path="screenshots/error.png")7.3 AI集成问题
Q7:API调用失败
# 检查API Key是否正确 echo $OPENAI_API_KEY # 检查网络连接 curl https://api.openai.com/v1/models
Q8:响应太慢
# 添加超时设置
response = self.client.chat.completions.create(
model="gpt-4",
messages=messages,
timeout=30 # 30秒超时
)🚀 八、快速开始
8.1 一键安装脚本
创建 install_env.ps1:
# 安装脚本
Write-Host "开始安装 Playwright 测试环境..." -ForegroundColor Cyan
# 1. 创建虚拟环境
python -m venv venv
.\venv\Scripts\activate
# 2. 安装依赖
pip install -r requirements.txt
# 3. 安装浏览器
python -m playwright install chromium
# 4. 验证安装
python -c "from playwright.sync_api import sync_playwright; print('安装成功 ✓')"
Write-Host "环境安装完成!" -ForegroundColor Green8.2 运行第一个测试
# 激活环境 .\venv\Scripts\activate # 运行测试 pytest tests/ -v # 只运行冒烟测试 pytest -m smoke -v # 生成HTML报告 pytest --html=reports/report.html --self-contained-html
8.3 在Trae中运行
1. 打开项目 2. 按 Ctrl+Shift+P 3. 输入 "Python: Run All Tests" 4. 查看测试结果
📚 九、资源链接
资源 | 链接 |
|---|---|
Playwright文档 | |
Playwright Python | |
Trae IDE | |
pytest文档 |
📝 结语
通过本文,您应该已经掌握了:
- ✅ Playwright环境配置
- ✅ Trae IDE使用
- ✅ AI集成方法
- ✅ 常见问题解决方案
下一步:
- 尝试运行第一个测试
- 学习Page Object模式
- 探索AI辅助测试开发
到此这篇关于Python Playwright UI自动化测试环境配置完全指南的文章就介绍到这了,更多相关Python Playwright 自动化测试环境内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
