# python-playwright
**Repository Path**: szwnba/python-playwright
## Basic Information
- **Project Name**: python-playwright
- **Description**: 学习基于python的playwright自动化UI测试框架
- **Primary Language**: Python
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 4
- **Created**: 2025-06-27
- **Last Updated**: 2025-06-27
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# python-playwright
#### 介绍
学习基于python的playwright自动化UI测试框架
#### 软件架构
1. python 3.8
2. playwright 1.31.1
#### 安装教程
1. 创建python虚拟环境
```bash
python -m venv xxx
```
> xxx替换为为自己的项目根目录,或者先进入到根目录,运行:python -m venv **.**
2. 激活虚拟环境
```bash
activate.bat
```
> activate.bat脚本在Scripts目录下
3. 安装依赖
```bash
pip install -r requirements.txt
```
> 注意:
> 1.设置国内镜像的方法:
> 2.使用国内镜像下载依赖时需要关闭VPN
> 3.官网没说要安装playwirght依赖,但实际上是需要的,pytest-playwright需要依赖此插件
> 4.插件安装的依赖列表:```pip list```
> 5.在虚拟环境中安装的依赖,也需要在虚拟环境中运行
4. 安装浏览器驱动
```bash
playwright install
```
5. 安装Allure命令行工具
!!!Allure需要Java 8环境
下载地址:
下载安装包:
> allure-2.24.0.zip
解压缩后得到4个目录:
> bin、config、lib、plugins
配置环境变量:
> 在Path中添加指向allure的bin目录,如:D:\software\allure-2.24.0\bin
> 注意解压目录不要有中文路径
检查是否安装成功:
> 打开CMD终端,运行:allure --version,出现版本号则成功
6. 改造pytest-playwright插件
当运行 pytest 命令时,pytest 会自动检测到 pytest-playwright 插件并加载它。
pytest-playwright 插件会自动加载与 pytest 结合使用的 Playwright 浏览器自动化测试。
它根据你的配置(如指定要使用的浏览器类型)来启动浏览器实例,并执行测试。
为什么要改造pytest-playwright插件?
为了直接在pytest-playwright插件中把截图、视频等加入到Allure测试报告!
参考博客:
(1)在/Lib/site-packages/pytest-playwright中找到原代码pytest-playwright.py,进行改造,具体详见:/plugins/my_pytest_playwright/my_pytest_playwright.py
(2)编写setup.py文件,描述打包信息,详见:/plugins/setup.py
(3)打包自定义插件,在/plugins下运行:```python setup.py sdist bdist_wheel```,此时会在/plugins目录下生成dist目录
(4)安装本地插件,在/plugins下运行:```pip install dist/my_pytest_playwright-0.1-py3-none-any.whl```
(5)卸载原插件:```pip uninstall pytest-playwright```
#### 使用说明
1. 录制
```bash
playeright codegen
```
> 运行命令后,会启动一个空白浏览器,和录制器,在浏览器中直接输入目标url打开网站即可
> 也可以直接直接打开:playwright codegen https://www.baidu.com
为了避免每次录制都要先登录,可以在第一次登录的时候缓存cookie:
```bash
playwright codegen --save-storage=auth.json http://127.0.0.1:34009/xxl-job-admin/toLogin
```
> --save-storage=auth.json 参数会在当前命令运行目录下创建auth.json保存cookie信息
在以后其他的测试用例的录制中,可以加载此cookie信息:
```bash
playwright open --load-storage=auth.json http://127.0.0.1:34009/xxl-job-admin/user
```
> --load-storage=auth.json 参数就是加载本地缓存的cookie
2. pytest
命名规则:
用例集:测试模块(test_\*.py,\*_test.py)
测试类-子模块(Test\_\*开头的类)
用例: 函数(test_开头的函数)
运行方式:
全局pytest运行配置文件:`pytest.ini`,放在项目跟目录下,以下三种运行方式都会受到该配置文件控制
(1)IDE插件运行:
以`IntelliJ IDEA`为例,需要先安装python开发插件,在进行以下设置:
File -> Settings -> Tools -> Python Integrated Tools -> Testing -> Default test runner设置为 ”pytest“
(2)python主入口运行:
参考`11_pytest_main.py`
(3)命令行运行:
参考`run.bat`
建议使用这种方式运行
#### 参与贡献
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request