Python Playwright UI自動(dòng)化測(cè)試環(huán)境配置完全指南
Playwright 是微軟出品的強(qiáng)大跨瀏覽器自動(dòng)化測(cè)試工具,相比 Selenium 具有更快的執(zhí)行速度、更好的穩(wěn)定性、更現(xiàn)代的API設(shè)計(jì)。本文詳細(xì)介紹如何在 Windows 環(huán)境下配置 Playwright 測(cè)試環(huán)境,并在 Trae IDE 中進(jìn)行開(kāi)發(fā)。
??? 一、環(huán)境準(zhǔn)備
1.1 系統(tǒng)要求
要求 | 推薦版本 |
|---|---|
操作系統(tǒng) | Windows 10/11 或 Windows Server 2019+ |
Python | Python 3.8+ |
內(nèi)存 | 8GB+ |
硬盤 | 10GB+ 可用空間 |
1.2 安裝 Python
推薦使用 Python 3.9 或 3.10/3.11 版本:
# 檢查Python版本 python --version # 如果未安裝,推薦使用 Python 3.11 # 下載地址:https://www.python.org/downloads/
安裝時(shí)注意:
- ? 勾選 "Add Python to PATH"
- ? 勾選 "Install pip"
- ? 推薦使用自定義安裝,選擇 "Python for all users"
?? 二、Playwright 依賴安裝
2.1 創(chuàng)建項(xiàng)目結(jié)構(gòu)
# 創(chuàng)建項(xiàng)目目錄 mkdir auto_ui cd auto_ui # 創(chuàng)建虛擬環(huán)境(推薦) python -m venv venv # 激活虛擬環(huán)境 .\venv\Scripts\activate # 如果遇到執(zhí)行策略問(wèn)題 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
2.2 安裝 Playwright
# 安裝Playwright(會(huì)包含測(cè)試框架) 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 創(chuàng)建依賴文件
# 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 # 日志和時(shí)間 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 使用系統(tǒng)Chrome
如果系統(tǒng)已安裝Chrome,可以直接使用,無(wú)需下載:
# 檢查系統(tǒng)Chrome路徑 Test-Path "C:\Program Files\Google\Chrome\Application\chrome.exe"
在代碼中啟用系統(tǒng)Chrome:
# conftest.py
@pytest.fixture(scope="function")
def browser_context(browser):
context = browser.new_context(
no_viewport=True,
channel='chrome', # 使用系統(tǒng)Chrome
)
context.set_default_timeout(TIMEOUT)
yield context
context.close()3.3 國(guó)內(nèi)鏡像安裝
清華鏡像(已停止維護(hù)):
# 已不推薦使用
推薦方案:使用代理或下載官方版本。
3.4 驗(yàn)證安裝
# 檢查版本
python -m playwright --version
# 檢查瀏覽器路徑
python -m playwright show-browser-path
# 驗(yàn)證瀏覽器可用
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 簡(jiǎn)介
Trae IDE 是基于 VS Code 的現(xiàn)代化 Python IDE,內(nèi)置 AI 輔助功能,非常適合自動(dòng)化測(cè)試開(kāi)發(fā)。
下載地址:https://trae.ai/
4.2 項(xiàng)目導(dǎo)入
# 方式1:直接打開(kāi)項(xiàng)目目錄 # 菜單 File → Open Folder → 選擇項(xiàng)目目錄 # 方式2:命令行打開(kāi) code .
4.3 Python 解釋器配置
1. 按 Ctrl+Shift+P 打開(kāi)命令面板 2. 輸入 "Python: Select Interpreter" 3. 選擇項(xiàng)目虛擬環(huán)境中的Python 路徑類似:項(xiàng)目路徑\venv\Scripts\python.exe
4.4 必裝插件
在 Trae IDE 擴(kuò)展市場(chǎng)中安裝:
插件名稱 | 用途 |
|---|---|
Python | Python語(yǔ)言支持 |
Pylance | Python類型檢查和智能提示 |
Ruff | Python代碼格式化 |
Playwright | Playwright測(cè)試支持 |
Error Lens | 錯(cuò)誤即時(shí)顯示 |
4.5 設(shè)置自動(dòng)測(cè)試
在 .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 賬號(hào) 2. 設(shè)置 → AI → 選擇模型 3. 可選模型: - Claude - GPT-4 - Gemini
?? 五、AI 模型配置
5.1 配置AI服務(wù)
創(chuàng)建 .env 文件(添加到 .gitignore):
# OpenAI配置 OPENAI_API_KEY=sk-xxxxx OPENAI_API_BASE=https://api.openai.com/v1 # Anthropic配置(Claude) ANTHROPIC_API_KEY=sk-ant-xxxxx # 國(guó)內(nèi)代理(如果需要) HTTP_PROXY=http://127.0.0.1:7890 HTTPS_PROXY=http://127.0.0.1:7890
5.2 AI輔助開(kāi)發(fā)示例
場(chǎng)景1:讓AI幫你寫測(cè)試用例
# 提示詞示例 """ 請(qǐng)幫我為這個(gè)登錄頁(yè)面寫測(cè)試用例: 頁(yè)面包含: - 用戶名輸入框 - 密碼輸入框 - 登錄按鈕 - 記住登錄復(fù)選框 請(qǐng)生成: 1. Page Object類結(jié)構(gòu) 2. 正常登錄測(cè)試 3. 錯(cuò)誤密碼測(cè)試 4. 空用戶名測(cè)試 """
場(chǎng)景2:讓AI幫你分析錯(cuò)誤
# 當(dāng)測(cè)試失敗時(shí),讓AI分析 """ 測(cè)試失敗了,日志顯示: - 錯(cuò)誤:ElementClickInterceptedException - 截圖已保存 頁(yè)面結(jié)構(gòu)可能發(fā)生了變化,請(qǐng)分析: 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分析測(cè)試錯(cuò)誤"""
prompt = f"""
測(cè)試自動(dòng)化執(zhí)行遇到錯(cuò)誤:
錯(cuò)誤信息:
{error_info}
請(qǐng)分析:
1. 最可能的原因?
2. 解決方案建議?
3. 如何避免類似問(wèn)題?
"""
response = self.client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content?? 六、項(xiàng)目配置結(jié)構(gòu)
6.1 目錄結(jié)構(gòu)
auto_ui/ ├── config/ # 配置目錄 │ ├── __init__.py │ ├── settings.py # Python配置 │ └── config.yaml # YAML配置 ├── pages/ # 頁(yè)面對(duì)象 │ ├── __init__.py │ ├── base_page.py │ └── login_page.py ├── tests/ # 測(cè)試用例 │ ├── __init__.py │ └── test_*.py ├── utils/ # 工具函數(shù) │ ├── __init__.py │ ├── logger.py │ └── decorators.py ├── conftest.py # pytest配置 ├── pytest.ini # pytest設(shè)置 └── 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)
# 配置項(xiàng)
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自動(dòng)化測(cè)試
smoke: 冒煙測(cè)試
regression: 回歸測(cè)試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()?? 七、常見(jiàn)問(wèn)題解決
7.1 安裝問(wèn)題
Q1:下載瀏覽器太慢
# 方案1:使用代理 $env:HTTPS_PROXY = "http://127.0.0.1:7890" python -m playwright install chromium # 方案2:使用系統(tǒng)Chrome(跳過(guò)下載) # 修改conftest.py,添加 channel='chrome'
Q2:安裝失敗,權(quán)限錯(cuò)誤
# 方案1:以管理員身份運(yùn)行 # 右鍵PowerShell → 以管理員身份運(yùn)行 # 方案2:清理后重試 Remove-Item -Recurse -Force "$env:LOCALAPPDATA\ms-playwright" python -m playwright install chromium
Q3:瀏覽器無(wú)法啟動(dòng)
# 檢查依賴 python -m playwright install-deps # 或者手動(dòng)安裝Visual C++ Redistributable
7.2 運(yùn)行問(wèn)題
Q4:測(cè)試超時(shí)
# 增加超時(shí)時(shí)間 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集成問(wèn)題
Q7:API調(diào)用失敗
# 檢查API Key是否正確 echo $OPENAI_API_KEY # 檢查網(wǎng)絡(luò)連接 curl https://api.openai.com/v1/models
Q8:響應(yīng)太慢
# 添加超時(shí)設(shè)置
response = self.client.chat.completions.create(
model="gpt-4",
messages=messages,
timeout=30 # 30秒超時(shí)
)?? 八、快速開(kāi)始
8.1 一鍵安裝腳本
創(chuàng)建 install_env.ps1:
# 安裝腳本
Write-Host "開(kāi)始安裝 Playwright 測(cè)試環(huán)境..." -ForegroundColor Cyan
# 1. 創(chuàng)建虛擬環(huán)境
python -m venv venv
.\venv\Scripts\activate
# 2. 安裝依賴
pip install -r requirements.txt
# 3. 安裝瀏覽器
python -m playwright install chromium
# 4. 驗(yàn)證安裝
python -c "from playwright.sync_api import sync_playwright; print('安裝成功 ?')"
Write-Host "環(huán)境安裝完成!" -ForegroundColor Green8.2 運(yùn)行第一個(gè)測(cè)試
# 激活環(huán)境 .\venv\Scripts\activate # 運(yùn)行測(cè)試 pytest tests/ -v # 只運(yùn)行冒煙測(cè)試 pytest -m smoke -v # 生成HTML報(bào)告 pytest --html=reports/report.html --self-contained-html
8.3 在Trae中運(yùn)行
1. 打開(kāi)項(xiàng)目 2. 按 Ctrl+Shift+P 3. 輸入 "Python: Run All Tests" 4. 查看測(cè)試結(jié)果
?? 九、資源鏈接
資源 | 鏈接 |
|---|---|
Playwright文檔 | |
Playwright Python | |
Trae IDE | |
pytest文檔 |
?? 結(jié)語(yǔ)
通過(guò)本文,您應(yīng)該已經(jīng)掌握了:
- ? Playwright環(huán)境配置
- ? Trae IDE使用
- ? AI集成方法
- ? 常見(jiàn)問(wèn)題解決方案
下一步:
- 嘗試運(yùn)行第一個(gè)測(cè)試
- 學(xué)習(xí)Page Object模式
- 探索AI輔助測(cè)試開(kāi)發(fā)
到此這篇關(guān)于Python Playwright UI自動(dòng)化測(cè)試環(huán)境配置完全指南的文章就介紹到這了,更多相關(guān)Python Playwright 自動(dòng)化測(cè)試環(huán)境內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)獲取視頻時(shí)長(zhǎng)功能
這篇文章主要介紹了Python如何實(shí)現(xiàn)獲取視頻時(shí)長(zhǎng)功能,可以精確到毫秒。文中的示例代碼簡(jiǎn)潔易懂,對(duì)我們的學(xué)習(xí)有一定的幫助,感興趣的可以了解一下2021-12-12
Python大數(shù)據(jù)用Numpy Array的原因解讀
一個(gè)Numpy數(shù)組由許多值組成,所有值的類型是相同的,Numpy 是Python科學(xué)計(jì)算的一個(gè)核心模塊,本文重點(diǎn)給大家介紹Python大數(shù)據(jù)Numpy Array的相關(guān)知識(shí),感興趣的朋友一起看看吧2022-02-02
Python中嵌套序列扁平化的多種實(shí)現(xiàn)方法詳解
在數(shù)據(jù)處理和算法設(shè)計(jì)中,嵌套序列扁平化是解決復(fù)雜問(wèn)題的關(guān)鍵技術(shù),Python提供了強(qiáng)大的工具來(lái)處理嵌套序列,下面小編就來(lái)和大家詳細(xì)介紹一下實(shí)現(xiàn)方法吧2025-09-09
python實(shí)現(xiàn)機(jī)械分詞之逆向最大匹配算法代碼示例
這篇文章主要介紹了python實(shí)現(xiàn)機(jī)械分詞之逆向最大匹配算法代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
使用Python實(shí)現(xiàn)Excel表格處理自動(dòng)化的方法技巧
在日常辦公中,Excel是最常用的數(shù)據(jù)處理工具之一,通過(guò)Python自動(dòng)化Excel操作,可以大幅提高工作效率,減少重復(fù)勞動(dòng),降低人為錯(cuò)誤,本文將介紹幾種常用的Python操作Excel的方法,并提供實(shí)用的代碼示例和應(yīng)用場(chǎng)景,需要的朋友可以參考下2026-01-01
Python獲取網(wǎng)頁(yè)數(shù)據(jù)詳解流程
讀萬(wàn)卷書不如行萬(wàn)里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Python來(lái)獲取網(wǎng)頁(yè)的數(shù)據(jù),主要應(yīng)用了Requests庫(kù),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2021-10-10
python計(jì)算兩個(gè)矩形框重合百分比的實(shí)例
今天小編就為大家分享一篇python計(jì)算兩個(gè)矩形框重合百分比的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
pycharm的debug調(diào)試以及異常,Python中錯(cuò)誤的處理過(guò)程
這篇文章主要介紹了pycharm的debug調(diào)試以及異常,Python中錯(cuò)誤的處理過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01

