python中Playwright 數(shù)據(jù)提取和驗證
數(shù)據(jù)提?。‥xtraction)和驗證(Assertion)是 Playwright 在自動化測試和爬蟲場景中最核心的部分。Playwright 提供了強大且可靠的 Locator API 和 Web-First 斷言,能自動等待元素就緒,確保測試穩(wěn)定。下面以 Node.js/TypeScript(Playwright Test)為主,附 Python 示例。
1.數(shù)據(jù)提取(常見方式)
| 提取目標(biāo) | 代碼示例(推薦 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[] 數(shù)組 |
| 多個元素內(nèi)文本 | const texts = await page.getByTestId('price').allInnerTexts(); | innerText(不含子元素隱藏文本) |
| 元素計數(shù) | const count = await page.getByRole('article').count(); | 返回元素數(shù)量 |
| 表格數(shù)據(jù)提取 | ```const | |
| JSON/API 數(shù)據(jù) | const response = await page.waitForResponse('**/api/users'); const json = await response.json(); | 攔截網(wǎng)絡(luò)響應(yīng)提取數(shù)據(jù) |
2.驗證(斷言)——Playwright 最強大特性
Playwright 的 expect 是 Web-First 斷言:會自動重試直到超時(默認(rèn) 30s),極大減少 flaky 測試。
import { test, expect } from '@playwright/test';
// 頁面標(biāo)題
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');
// 元素數(shù)量
await expect(page.getByRole('listitem')).toHaveCount(5);
// Checkbox/Radio 狀態(tài)
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.高級驗證技巧
// 軟斷言(不立即失敗,繼續(xù)執(zhí)行)
expect.soft(page.getByText('錯誤提示')).toBeHidden();
// 自定義超時
await expect(page.getByText('加載完成'), { timeout: 10000 }).toBeVisible();
// 輪詢斷言(復(fù)雜條件)
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.實戰(zhàn)示例:提取并驗證搜索結(jié)果
test('百度搜索 Playwright 并驗證結(jié)果', async ({ page }) => {
await page.goto('https://www.baidu.com');
await page.getByLabel('搜索輸入框').fill('Playwright');
await page.getByRole('button', { name: '百度一下' }).click();
// 等待結(jié)果加載
await page.waitForLoadState('networkidle');
// 提取第一個結(jié)果標(biāo)題
const firstTitle = await page.getByRole('heading').first().textContent();
console.log('第一個結(jié)果標(biāo)題:', firstTitle);
// 驗證結(jié)果包含關(guān)鍵詞
await expect(page.getByRole('heading').first()).toContainText('Playwright');
await expect(page.getByRole('heading')).toHaveCount(10); // 通常一頁 10 條
// 提取所有結(jié)果鏈接
const links = await page.getByRole('link', { name: /Playwright/ }).all();
console.log(`找到 ${links.length} 個相關(guān)鏈接`);
});
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"標(biāo)題: {title}, 副標(biāo)題: {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()
最佳實踐總結(jié)
- 提取:優(yōu)先用
getByRole+textContent()/inputValue()。 - 驗證:全部使用
expect(),讓 Playwright 自動重試。 - 測試專用屬性:在被測應(yīng)用中添加
data-testid="xxx",最穩(wěn)定。 - 調(diào)試:失敗時自動生成 trace(截圖 + 視頻 + 網(wǎng)絡(luò)日志),用
npx playwright show-trace查看。
到此這篇關(guān)于python中Playwright 數(shù)據(jù)提取和驗證的文章就介紹到這了,更多相關(guān)Playwright 數(shù)據(jù)提取和驗證內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽
相關(guān)文章
Django def clean()函數(shù)對表單中的數(shù)據(jù)進(jìn)行驗證操作
這篇文章主要介紹了Django def clean()函數(shù)對表單中的數(shù)據(jù)進(jìn)行驗證操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Python使用matplotlib填充圖形指定區(qū)域代碼示例
這篇文章主要介紹了Python使用matplotlib填充圖形指定區(qū)域代碼示例,具有一定借鑒價值,需要的朋友可以參考下2018-01-01

