Playwright Data Extraction and Validation
Data extraction and validation are key to automated testing, mainly includingretrieving page data, assertion validation, screenshots, and recording, which not only verify whether functionality is correct, but also assist with debugging and regression testing.
Element Information Retrieval
In testing, you often need to read page information for validation. Playwright provides a rich set of APIs.
1. Get Text Content
Example
const text = await page.textContent('#welcome');
console.log(text);
// Get the text of multiple elements
const items = await page.$$eval('.list-item', els => els.map(e => e.textContent));
console.log(items);
2. Get Attribute Values
const value = await page.getAttribute('#username', 'placeholder');
console.log(value); // "请输入用户名"
3. Get Style Information
// 获取元素的 style 属性
const color = await page.$eval('#btn', el => getComputedStyle(el).color);
console.log(color);
4. Element State Checking
await page.isVisible('#dialog'); // 是否可见
await page.isHidden('#loading'); // 是否隐藏
await page.isEnabled('#submit'); // 是否可用
await page.isDisabled('#submit'); // 是否禁用
await page.isChecked('#agree'); // 复选框是否选中
Assertions and Validation
Playwright providesa built-in assertion library(@playwright/test), making it easy to write test cases.
1. Built-in Assertion Methods
In@playwright/testIn , useexpectfor assertions.
Example
test('Validation Example', async ({ page }) => {
await page.goto('https://example.com');
// Text assertion
await expect(page.locator('h1')).toHaveText('Example Domain');
// Attribute assertion
await expect(page.locator('a')).toHaveAttribute('href', 'https://www.iana.org/domains/example');
// Visibility assertion
await expect(page.locator('h1')).toBeVisible();
});
2. Text Content Validation
await expect(page.locator('#message')).toHaveText('登录成功');
await expect(page.locator('#username')).toHaveValue('testuser');
3. Element State Validation
await expect(page.locator('#submit')).toBeEnabled();
await expect(page.locator('#agree')).toBeChecked();
await expect(page.locator('#loading')).toBeHidden();
4. Page Title and URL Validation
await expect(page).toHaveTitle(/Playwright/);
await expect(page).toHaveURL('https://playwright.dev/');
Screenshots and Recording
Screenshots and recording are very useful in debugging, failure case analysis, and regression testing.
1. Page Screenshot
await page.screenshot({ path: 'screenshot.png', fullPage: true });
path: Save pathfullPage: Whether to capture the entire page
2. Element Screenshot
const element = page.locator('#logo');
await element.screenshot({ path: 'logo.png' });
3. Video Recording
When creatingcontext, enable recording:
const context = await browser.newContext({
recordVideo: { dir: 'videos/' }
});
const page = await context.newPage();
await page.goto('https://example.com');
await context.close(); // 关闭后保存视频
4. Screenshot Comparison (Snapshot Testing)
Playwright supports snapshot comparison, commonly used in regression testing.
import { test, expect } from '@playwright/test';
test('页面快照测试', async ({ page }) => {
await page.goto('https://playwright.dev');
expect(await page.screenshot()).toMatchSnapshot('homepage.png');
});
It compares screenshots with baseline imageshomepage.pngto detect UI changes.
Okay ✅ Then I willChapter 6: Data Extraction and Validationadd acomplete practical case, and compilean API comparison table. This way you will have both practical experience and a quick reference table.
Practical Case — Login Validation and Screenshot Snapshot
This case covers:Information extraction + assertion validation + page screenshots。
Example
import { test, expect } from '@playwright/test';
test('User login and verify results', async ({ page }) => {
// 1. Open the login page
await page.goto('https://example.com/login');
// 2. Enter username and password
await page.fill('#username', 'testuser');
await page.fill('#password', 'Password123');
// 3. Click login
await page.click('#submit');
// 4. Wait for redirect and check title
await expect(page).toHaveTitle(/Dashboard/);
// 5. Verify welcome text
await expect(page.locator('.welcome')).toHaveText('Welcome, testuser');
// 6. Check button state
await expect(page.locator('#logout')).toBeVisible();
await expect(page.locator('#logout')).toBeEnabled();
// 7. Get user ID attribute and verify
const userId = await page.getAttribute('#user-profile', 'data-id');
console.log('User ID:', userId);
expect(userId).not.toBeNull();
// 8. Page screenshot
await page.screenshot({ path: 'login-success.png', fullPage: true });
// 9. Snapshot comparison (UI regression testing)
expect(await page.screenshot()).toMatchSnapshot('dashboard.png');
});
This test will verify:
- Whether the page title and welcome text are correct
- Whether elements are visible / enabled
- Whether the user info attribute exists
- Page screenshot and UI snapshot comparison
Common API Table
Below isdata extraction and validationrelated API overview table.
| Method | Description | Example |
|---|---|---|
page.textContent(selector) |
Get element text content | await page.textContent('#msg') |
page.innerText(selector) |
Get rendered plain text | await page.innerText('#msg') |
page.innerHTML(selector) |
Get element HTML | await page.innerHTML('#content') |
page.getAttribute(selector, name) |
Get attribute value | await page.getAttribute('#btn', 'class') |
page.$eval(selector, fn) |
Execute a function on the element | await page.$eval('#logo', el => el.tagName) |
page.$$eval(selector, fn) |
Execute functions in batch | await page.$$eval('.item', els => els.length) |
page.isVisible(selector) |
Is visible | await page.isVisible('#dialog') |
page.isHidden(selector) |
Is hidden | await page.isHidden('#loading') |
page.isEnabled(selector) |
Is enabled | await page.isEnabled('#submit') |
page.isDisabled(selector) |
Is disabled | await page.isDisabled('#submit') |
page.isChecked(selector) |
Is checked | await page.isChecked('#agree') |
Assertions and Validation (@playwright/test)
| Method | Description | Example |
|---|---|---|
expect(locator).toHaveText(value) |
Verify text | expect(page.locator('h1')).toHaveText('欢迎') |
expect(locator).toHaveValue(value) |
Verify input value | expect(page.locator('#user')).toHaveValue('test') |
expect(locator).toHaveAttribute(name, value) |
Verify attribute | expect(page.locator('#btn')).toHaveAttribute('type', 'submit') |
expect(locator).toBeVisible() |
Element is visible | expect(page.locator('#msg')).toBeVisible() |
expect(locator).toBeHidden() |
Element is hidden | expect(page.locator('#loading')).toBeHidden() |
expect(locator).toBeEnabled() |
Element is enabled | expect(page.locator('#submit')).toBeEnabled() |
expect(locator).toBeDisabled() |
Element is disabled | expect(page.locator('#submit')).toBeDisabled() |
expect(locator).toBeChecked() |
Element is checked | expect(page.locator('#agree')).toBeChecked() |
expect(page).toHaveTitle(title) |
Page title verification | expect(page).toHaveTitle(/Dashboard/) |
expect(page).toHaveURL(url) |
Page URL verification | expect(page).toHaveURL('https://example.com/dashboard') |
Screenshots and Recording
| Method | Description | Example |
|---|---|---|
page.screenshot(options) |
Page screenshot | await page.screenshot({ path: 'page.png' }) |
locator.screenshot(options) |
Element screenshot | await page.locator('#logo').screenshot({ path: 'logo.png' }) |
context = browser.newContext({ recordVideo }) |
Enable video recording | recordVideo: { dir: 'videos/' } |
expect(await page.screenshot()).toMatchSnapshot(name) |
Screenshot comparison (snapshot testing) | expect(await page.screenshot()).toMatchSnapshot('home.png') |