python中Playwright 數(shù)據(jù)提取和驗證
數(shù)據(jù)提?。‥xtraction)和驗證(Assertion)是 Playwright 在自動化測試和爬蟲場景中最核心的部分。Playwright 提供了強(qiáng)大且可靠的 Locator API 和 Web-First 斷言,能自動等待元素就緒,確保測試穩(wěn)定。下面以 Node.js/TypeScript(Playwright Test)為主,附 Python 示例。
1.數(shù)據(jù)提?。ǔR姺绞剑?/h2>
| 提取目標(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 最強(qiáng)大特性
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)文章
Python中venv虛擬環(huán)境超詳細(xì)講解
虛擬環(huán)境是一個獨立的Python環(huán)境,它與系統(tǒng)的全局Python環(huán)境隔離,這篇文章主要介紹了Python中venv虛擬環(huán)境的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-04-04
使用Selenium在Python中實現(xiàn)錄屏功能
Selenium 是一個強(qiáng)大的用于自動化測試的工具,但你知道它也可以用來錄制瀏覽器操作的視頻嗎?本文將介紹如何使用 Selenium 在 Python 中實現(xiàn)錄屏功能,以便記錄和分享你的網(wǎng)頁操作過程,需要的朋友可以參考下2023-11-11
Python import與from import使用及區(qū)別介紹
Python程序可以調(diào)用一組基本的函數(shù)(即內(nèi)建函數(shù)),比如print()、input()和len()等函數(shù)。接下來通過本文給大家介紹Python import與from import使用及區(qū)別介紹,感興趣的朋友一起看看吧2018-09-09
用Python+OpenCV對比圖像質(zhì)量的幾種方法
這篇文章主要介紹了用Python+OpenCV對比圖像質(zhì)量過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-07-07
與Django結(jié)合利用模型對上傳圖片預(yù)測的實例詳解
今天小編就為大家分享一篇與Django結(jié)合利用模型對上傳圖片預(yù)測詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08

