数据提取(extraction)和验证(assertion)是 playwright 在自动化测试和爬虫场景中最核心的部分。playwright 提供了强大且可靠的 locator api 和 web-first 断言,能自动等待元素就绪,确保测试稳定。下面以 node.js/typescript(playwright test)为主,附 python 示例。
1.数据提取(常见方式)
| 提取目标 | 代码示例(推荐 locator) | 说明 |
|---|---|---|
| 单个元素文本 | const text = await page.getbyrole('heading', { name: '欢迎' }).textcontent(); | 返回字符串(null 如果不存在) |
| 输入框值 | const value = await page.getbylabel('用户名').inputvalue(); | 适用于 input/textarea |
| 属性值 | const href = await page.getbyrole('link', { name: '详情' }).getattribute('href'); | 获取 href、src、data-* 等 |
| 多个元素文本 | const items = await page.getbyrole('listitem').alltextcontents(); | 返回 string[] 数组 |
| 多个元素内文本 | const texts = await page.getbytestid('price').allinnertexts(); | innertext(不含子元素隐藏文本) |
| 元素计数 | const count = await page.getbyrole('article').count(); | 返回元素数量 |
| 表格数据提取 | ```const | |
| json/api 数据 | const response = await page.waitforresponse('**/api/users'); const json = await response.json(); | 拦截网络响应提取数据 |
2.验证(断言)——playwright 最强大特性
playwright 的 expect 是 web-first 断言:会自动重试直到超时(默认 30s),极大减少 flaky 测试。
import { test, expect } from '@playwright/test';
// 页面标题
await expect(page).tohavetitle('playwright - 首页');
await expect(page).tohavetitle(/playwright/); // 正则匹配
// url
await expect(page).tohaveurl('https://playwright.dev/');
await expect(page).tohaveurl(/docs/);
// 元素可见/隐藏
await expect(page.getbytext('加载成功')).tobevisible();
await expect(page.getbytext('加载中')).tobehidden();
// 元素文本
await expect(page.getbyrole('heading')).tohavetext('欢迎使用');
await expect(page.getbytestid('status')).tocontaintext('成功'); // 包含
// 元素属性
await expect(page.getbyrole('link')).tohaveattribute('href', '/docs');
await expect(page.getbyrole('img')).tohaveattribute('src', /logo/);
// 输入框值
await expect(page.getbylabel('搜索')).tohavevalue('playwright');
// 元素数量
await expect(page.getbyrole('listitem')).tohavecount(5);
// checkbox/radio 状态
await expect(page.getbyrole('checkbox')).tobechecked();
await expect(page.getbyrole('radio', { name: '男' })).tobechecked();
// 元素启用/禁用
await expect(page.getbyrole('button')).tobeenabled();
await expect(page.getbyrole('button')).tobedisabled();
3.高级验证技巧
// 软断言(不立即失败,继续执行)
expect.soft(page.getbytext('错误提示')).tobehidden();
// 自定义超时
await expect(page.getbytext('加载完成'), { timeout: 10000 }).tobevisible();
// 轮询断言(复杂条件)
await expect(async () => {
const count = await page.getbyrole('listitem').count();
expect(count).tobegreaterthan(0);
}).topass({ timeout: 15000 });
// 截图断言(视觉回归)
await expect(page).tohavescreenshot('homepage.png', { maxdiffpixels: 100 });
// 全页面截图比较(像素级)
await expect(page).tohavescreenshot({ fullpage: true });
4.实战示例:提取并验证搜索结果
test('百度搜索 playwright 并验证结果', async ({ page }) => {
await page.goto('https://www.baidu.com');
await page.getbylabel('搜索输入框').fill('playwright');
await page.getbyrole('button', { name: '百度一下' }).click();
// 等待结果加载
await page.waitforloadstate('networkidle');
// 提取第一个结果标题
const firsttitle = await page.getbyrole('heading').first().textcontent();
console.log('第一个结果标题:', firsttitle);
// 验证结果包含关键词
await expect(page.getbyrole('heading').first()).tocontaintext('playwright');
await expect(page.getbyrole('heading')).tohavecount(10); // 通常一页 10 条
// 提取所有结果链接
const links = await page.getbyrole('link', { name: /playwright/ }).all();
console.log(`找到 ${links.length} 个相关链接`);
});
5.python 版提取与验证示例
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=false)
page = browser.new_page()
page.goto("https://playwright.dev")
# 提取
title = page.title()
heading = page.get_by_role("heading", name="fast and reliable").text_content()
print(f"标题: {title}, 副标题: {heading}")
# 验证
expect(page).to_have_title("playwright")
expect(page.get_by_role("link", name="get started")).to_be_visible()
expect(page.get_by_text("playwright is a")).to_contain_text("reliable")
browser.close()
最佳实践总结
- 提取:优先用
getbyrole+textcontent()/inputvalue()。 - 验证:全部使用
expect(),让 playwright 自动重试。 - 测试专用属性:在被测应用中添加
data-testid="xxx",最稳定。 - 调试:失败时自动生成 trace(截图 + 视频 + 网络日志),用
npx playwright show-trace查看。
到此这篇关于python中playwright 数据提取和验证的文章就介绍到这了,更多相关playwright 数据提取和验证内容请搜索代码网以前的文章或继续浏览
发表评论