零基础实现 Web 自动化全流程测试教程(Python + Selenium + Pytest + Allure)_python+pytest+selenium自动化基础
🧪 零基础实现 Web 自动化全流程测试教程(Python + Selenium + Pytest + Allure)
🎯 一、目标
帮助零基础用户掌握自动化测试的基本流程,使用 Python 搭配 Selenium 实现 Web 页面操作,使用 Pytest 编写和执行测试用例,并使用 Allure 生成可视化测试报告。
本教程特别强调 Pytest 的 fixture 功能,帮助你理解如何通过 fixture 提升测试脚本的结构清晰度与可维护性。
🛠️ 二、所需工具与环境
pip install selenium
或 PyCharm 安装pip install pytest
pip install allure-pytest
📦 三、安装步骤详解
1. 安装 Python
- 官网地址:https://www.python.org/
- 安装时勾选 Add to PATH
- 验证:
python --version
2. 安装 PyCharm
- 推荐使用社区版
- 安装完成后配置项目解释器路径为 Python.exe 所在目录
3. 安装 Selenium(两种方式)
✅ 方式一:命令行安装(CMD)
pip install selenium
验证:
pip show selenium
✅ 方式二:PyCharm 图形界面安装
- Settings → Project: your_project_name → Python Interpreter
- 点击
+
号 → 搜索selenium
→ 安装
4. 安装浏览器及驱动
- Chrome 下载:https://www.google.cn/chrome/fallback/
- 驱动下载地址:https://googlechromelabs.github.io/chrome-for-testing/
- 将
chromedriver.exe
添加到系统环境变量PATH
中
5. 安装 Pytest
pip install pytest
验证:
pytest --version或者pytest --alluredir=report --version或者pip show allure-pytest
6. 安装 Allure 插件
pip install allure-pytest
验证:
pip show allure-pytest
7. 安装 Allure 命令行工具(Allure CLI)
✅ 方式一:npm 安装(推荐)
确保已安装 Node.js 和 npm:
npm install -g allure-commandline --save-dev
✅ 方式二:手动下载安装
- 下载地址:https://github.com/allure-framework/allure2/releases
- 解压后将
bin
目录加入系统环境变量PATH
- 验证:
allure --version
🧰 四、工具简介与角色说明(含 Pytest fixture 详解)
1. 🧪 Selenium —— Web 自动化测试核心库
- 作用:模拟用户操作浏览器,完成页面点击、输入、查找等行为。
- 常用方法:
find_element()
查找元素click()
点击按钮send_keys()
输入文本get_attribute()
获取属性值text
获取文本内容
2. 🧪 Pytest —— 自动化测试框架
- 作用:组织、运行测试脚本,提供断言、参数化、Fixture 等功能。
- 特点:
- 自动发现测试文件(以
test_*.py
开头) - 支持参数化测试
- 提供 fixture 管理初始化和清理逻辑
- 输出详细失败信息,便于调试
- 自动发现测试文件(以
🔁 Pytest 中的 fixture
说明与作用
📌 什么是 fixture?
fixture 是 Pytest 提供的一种机制,用于为测试函数提供前置准备和后置清理操作。它使得测试代码更加模块化、可重用、易维护。
✅ fixture 的主要作用
yield
或 addfinalizer
在测试结束后自动清理资源🔄 fixture 的作用域(scope)
function
(默认)module
.py
文件中所有测试只执行一次package
session
示例:浏览器初始化 fixture
import pytestfrom selenium import webdriver@pytest.fixture(scope=\"module\")def browser(): driver = webdriver.Chrome() yield driver driver.quit()
📦 fixture 的定义方式
方式一:使用 @pytest.fixture
装饰器定义
import pytest@pytest.fixturedef sample_data(): return {\"username\": \"testuser\", \"password\": \"123456\"}
方式二:使用 conftest.py
共享 fixtures
将常用 fixture 定义在项目根目录或模块目录下的 conftest.py
文件中,供多个测试文件复用。
project/├── tests/│ ├── conftest.py│ └── test_login.py└── utils/ └── helpers.py
💡 fixture 的使用示例
示例 1:基础使用(传递测试数据)
import pytest@pytest.fixturedef user_info(): return {\"username\": \"admin\", \"role\": \"superuser\"}def test_user_role(user_info): assert user_info[\"role\"] == \"superuser\"
示例 2:浏览器初始化(结合 Selenium)
import pytestfrom selenium import webdriver@pytest.fixture(scope=\"module\")def browser(): driver = webdriver.Chrome() yield driver driver.quit()def test_login(browser): browser.get(\"https://example.com/login\") # 输入用户名密码、点击登录按钮等操作 assert \"dashboard\" in browser.current_url
示例 3:使用 yield
进行清理操作
import pytest@pytest.fixturedef temp_file(tmpdir): path = tmpdir.join(\"temp.txt\") with open(path, \"w\") as f: f.write(\"test content\") yield path # 测试结束后自动删除文件
⚙️ fixture 高级特性
1. 参数化 fixture(Parametrize)
可以为 fixture 设置多组输入参数,实现更灵活的测试组合。
import pytest@pytest.fixture(params=[\"chrome\", \"firefox\"])def browser(request): if request.param == \"chrome\": driver = webdriver.Chrome() elif request.param == \"firefox\": driver = webdriver.Firefox() yield driver driver.quit()
2. 自动应用 fixture(Autouse)
无需手动传参即可自动触发 fixture。
@pytest.fixture(autouse=True)def setup_database(): connect_db() yield disconnect_db()
3. 多 fixture 嵌套依赖
一个 fixture 可以依赖另一个 fixture。
@pytest.fixturedef db_connection(): conn = create_connection() yield conn conn.close()@pytest.fixturedef user(db_connection): return db_connection.get_user(\"testuser\")
3. 📊 Allure-pytest —— 测试报告插件
- 作用:记录测试过程并生成结构化数据,用于后续生成可视化报告。
- 配合 Allure CLI 使用,支持 HTML 报告展示、CI 集成等。
📊 五、使用 DeepSeek 生成测试脚本(可选)
示例提示词:使用结构化的表达,可提高精准率。结构化公式:角色+任务+背景+要求
- 角色:一名自动化测试工程师小白
- 任务:编写自动化测试脚本
- 背景:你擅长python、selenium
- 环境:https://example.com/login
- 要求:
1、使用python+selenium技术
2、根据测试步骤实现
3、每句代码要写注释
4、定位方式使用CSS_SELECTOR- 输出:python自动化脚本
- 步骤:
1.输入用户名xxx
2.输入密码123456
3.输入图片验证码8888
4.点击登录按钮
DeepSeek 返回示例代码:
from selenium import webdriverfrom selenium.webdriver.common.by import Byimport timedriver = webdriver.Chrome()driver.get(\"https://example.com/login\")# 输入用户名和密码\"\"\"1.元素定位方式:8种·ID:唯一·CSS SELECTOR::使用选择器定位,速度快·XPATH:使用元素位置定位,稳定性差2.AI写脚本元素定位解决方案AI写步骤,手动写定位方式AI写步骤的时候,将元素信息给AI\"\"\"driver.find_element(By.ID, \"username\").send_keys(\"testuser\")driver.find_element(By.ID, \"password\").send_keys(\"password123\")# 点击登录按钮driver.find_element(By.XPATH, \"//button[@type=\'submit\']\").click()time.sleep(2)# 断言跳转或文本assert \"dashboard\" in driver.current_url or \"欢迎\" in driver.page_sourcedriver.quit()
🧱 六、使用 Pytest 编写测试用例
创建 test_login.py
import pytestfrom selenium import webdriverfrom selenium.webdriver.common.by import Byimport time@pytest.fixture(scope=\"module\")def browser(): driver = webdriver.Chrome() yield driver driver.quit()def test_login(browser): browser.get(\"https://example.com/login\") browser.find_element(By.ID, \"username\").send_keys(\"testuser\") browser.find_element(By.ID, \"password\").send_keys(\"password123\") browser.find_element(By.XPATH, \"//button[@type=\'submit\']\").click() time.sleep(2) assert \"dashboard\" in browser.current_url or \"欢迎\" in browser.page_source
📊 七、生成 Allure 测试报告
1. 执行测试并生成结果数据
pytest test_login.py --alluredir=./report
2. 查看报告
allure serve ./report
📌 八、常见问题排查指南
no tests ran in 0.02s
test_*.py
开头,测试函数以 test_*
开头ModuleNotFoundError: No module named \'selenium\'
pip install selenium
WebDriverException: Message: \'chromedriver\' executable needs to be in PATH
AssertionError
🔁 九、整体流程图解
[用户] ↓[编写测试逻辑] ↓[Selenium] —— 控制浏览器进行页面操作 ↓[Pytest] ——— 组织测试用例,执行测试,断言结果 ↓[Allure-pytest] —— 记录测试过程,生成报告数据 ↓[Allure CLI] —— 生成 HTML 可视化报告
✅ 十、总结
conftest.py
统一管理公共 fixture,提高代码复用率通过熟练掌握 fixture
,你可以显著提升自动化测试脚本的结构清晰度、可维护性和复用性。它是 Pytest 成为现代测试框架首选的重要原因之一。
学习笔记 2025/05/21