头像
淇迹时刻
-- : -- : --
切换主题色
-- : -- : --

第六阶段:UI自动化实战

最后更新于:

第六阶段:UI自动化实战

一、环境准备

1.1 安装Playwright

1pip install playwright
2pip install pytest-playwright

1.2 安装浏览器

1playwright install

1.3 检查安装

1pip list | findstr playwright
2# playwright 1.40.0
3# pytest-playwright 0.7.1

二、Playwright基础

2.1 浏览器操作

1from playwright.sync_api import sync_playwright
2
3with sync_playwright() as p:
4    browser = p.chromium.launch(headless=False)
5    page = browser.new_page()
6    page.goto("https://example.com")
7    print(page.title())
8    browser.close()

2.2 浏览器类型

浏览器名称特点
Chromiump.chromium开源版Chrome,最常用
Firefoxp.firefoxMozilla Firefox
WebKitp.webkitSafari内核

2.3 运行模式

模式说明适用场景
headless=True无头模式,无界面CI/CD环境
headless=False有头模式,显示浏览器调试阶段

三、元素定位

3.1 CSS选择器

 1# 通过ID定位
 2page.locator("#username")
 3
 4# 通过class定位
 5page.locator(".btn-primary")
 6
 7# 通过标签名定位
 8page.locator("input")
 9
10# 通过属性定位
11page.locator('[name="email"]')
12
13# 组合选择器
14page.locator("form#login-form input[type='text']")

3.2 XPath选择器

1# 绝对路径
2page.locator('//html/body/div/form/input')
3
4# 相对路径
5page.locator('//input[@name="username"]')
6
7# 包含文本
8page.locator('//button[contains(text(), "登录")]')

3.3 文本定位

1# 精确匹配
2page.locator("text=登录")
3
4# 模糊匹配
5page.locator("text*=登")
6
7# 正则匹配
8page.locator("text=/^登/")

四、页面操作

4.1 导航

1page.goto("https://example.com")
2page.go_back()
3page.go_forward()
4page.reload()

4.2 输入

1page.fill("#username", "testuser")
2page.type("#password", "password123")

4.3 点击

1page.click("#login-btn")
2page.dblclick("#double-click-btn")
3page.click("#checkbox", click_count=2)

4.4 等待

1# 等待元素可见
2page.wait_for_selector("#success-message")
3
4# 等待页面加载
5page.wait_for_load_state("networkidle")
6
7# 强制等待
8page.wait_for_timeout(1000)  # 毫秒

4.5 获取元素信息

 1# 获取文本
 2text = page.locator("#title").text_content()
 3
 4# 获取属性
 5value = page.locator("#username").get_attribute("value")
 6
 7# 获取数量
 8count = page.locator("li").count()
 9
10# 判断可见性
11is_visible = page.locator("#element").is_visible()

五、pytest-playwright集成

5.1 内置fixture

fixture说明作用域
browser浏览器实例session
context浏览器上下文function
page页面实例function

5.2 自定义fixture

 1# tests/ui/conftest.py
 2import pytest
 3
 4@pytest.fixture(scope="function")
 5def browser_context(browser):
 6    context = browser.new_context(base_url="http://127.0.0.1:8000")
 7    yield context
 8    context.close()
 9
10@pytest.fixture(scope="function")
11def page(browser_context):
12    page = browser_context.new_page()
13    yield page
14    page.close()

5.3 运行命令

 1# 指定浏览器运行
 2pytest tests/ui/ --browser=chromium
 3pytest tests/ui/ --browser=firefox
 4pytest tests/ui/ --browser=webkit
 5
 6# 多个浏览器并行运行
 7pytest tests/ui/ --browser=chromium --browser=firefox
 8
 9# 无头模式运行
10pytest tests/ui/ --browser=chromium --headless

六、示例代码

6.1 UI测试示例

 1# tests/ui/test_user_management.py
 2import pytest
 3
 4class TestUserManagementUI:
 5    def test_page_title(self, page):
 6        page.goto("/")
 7        assert page.title() == "用户管理系统"
 8
 9    def test_page_heading(self, page):
10        page.goto("/")
11        heading = page.locator("h1")
12        assert heading.text_content() == "用户管理系统"
13
14    def test_user_table_display(self, page):
15        page.goto("/")
16        table = page.locator("#user-table")
17        assert table.is_visible()
18        rows = table.locator("tr")
19        assert rows.count() >= 3
20
21    def test_add_user(self, page):
22        page.goto("/")
23        initial_count = page.locator("#user-table tr").count()
24        
25        page.fill("#name", "测试用户")
26        page.fill("#email", "testui@example.com")
27        page.click("#vip")
28        page.click("#add-btn")
29        
30        page.wait_for_timeout(500)
31        
32        new_count = page.locator("#user-table tr").count()
33        assert new_count == initial_count + 1
34
35    def test_user_table_content(self, page):
36        page.goto("/")
37        table = page.locator("#user-table")
38        assert "张三" in table.text_content()
39        assert "李四" in table.text_content()

6.2 页面模型模式

 1# tests/ui/pages/user_management_page.py
 2class UserManagementPage:
 3    def __init__(self, page):
 4        self.page = page
 5        self.name_input = page.locator("#name")
 6        self.email_input = page.locator("#email")
 7        self.vip_checkbox = page.locator("#vip")
 8        self.add_button = page.locator("#add-btn")
 9        self.user_table = page.locator("#user-table")
10
11    def navigate(self):
12        self.page.goto("/")
13
14    def add_user(self, name, email, vip=False):
15        self.name_input.fill(name)
16        self.email_input.fill(email)
17        if vip:
18            self.vip_checkbox.click()
19        self.add_button.click()
20
21    def get_user_count(self):
22        return self.user_table.locator("tr").count()

6.3 使用页面模型的测试

 1def test_add_user_with_page_model(page):
 2    user_page = UserManagementPage(page)
 3    user_page.navigate()
 4    
 5    initial_count = user_page.get_user_count()
 6    user_page.add_user("测试用户", "test@example.com", vip=True)
 7    
 8    page.wait_for_timeout(500)
 9    
10    assert user_page.get_user_count() == initial_count + 1

七、易错点与注意事项

7.1 常见错误

  1. 元素定位不稳定:使用动态ID或不稳定的选择器
  2. 等待时间不足:页面加载完成前进行操作
  3. 浏览器兼容性:不同浏览器的行为差异
  4. 测试数据污染:没有正确清理测试数据
  5. 网络问题:网络延迟导致请求失败

7.2 最佳实践

  1. 使用稳定的元素定位方式(ID、name、data-testid)
  2. 使用显式等待代替强制等待
  3. 在CI/CD环境使用无头模式
  4. 使用fixture管理浏览器生命周期
  5. 使用页面模型模式封装页面操作

八、小结

本阶段学习了UI自动化实战,包括:

  • Playwright的安装和配置
  • 浏览器操作和元素定位
  • 页面操作和等待策略
  • pytest-playwright集成
  • 页面模型模式
  • 运行命令和参数
最新文章