Playwright Data Extraction and Validation
Data extraction and validation are key to automated testing, mainly including retrieving page data, assertion validation, screenshots, and recordingNot only can they verify whether functionality is correct, but they also assist in debugging and regression testing.
Element Information Retrieval
In tests you often need to read page information for verification, and Playwright provides a rich set of APIs.
1. Getting Text Content
Example
// Get the text of a single element
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. Getting Attribute Values
const value = await page.getAttribute('#username', 'placeholder');
console.log(value); // "请输入用户名"
3. Getting Style Information
// Get the element's style attribute
const color = await page.$eval('#btn', el => getComputedStyle(el).color);
console.log(color);
4. Checking Element State
await page.isVisible('#dialog'); // 是否可见
await page.isHidden('#loading'); // 是否隐藏
await page.isEnabled('#submit'); // 是否可用
await page.isDisabled('#submit'); // 是否禁用
await page.isChecked('#agree'); // 复选框是否选中
Assertions and Validation
Playwright provides a built-in assertion library(@playwright/test), making it easy to write test cases.
1. Built-in Assertion Methods
in @playwright/test In it, use expect to make assertions.
Example
import
{
test
,
expect
}
from
'@playwright/test'
;
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, failed-case analysis, and regression testing.
1. Page Screenshots
await page.screenshot({ path: 'screenshot.png', fullPage: true });
path: Save pathfullPage: Whether to capture the full page
2. Element Screenshots
const element = page.locator('#logo');
await element.screenshot({ path: 'logo.png' });
3. Video Recording
When creating a context , 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 the screenshot with a baseline image homepage.png to detect UI changes.
OK ✅ Then let me add a Chapter 6: Data Extraction and Validation supplement with a complete hands-on case, and organize an API reference table. This way you get both hands-on practice and a quick reference.
Hands-On Case - Login Validation and Screenshot Snapshots
This case covers:Information extraction + assertion validation + page screenshots。
Example
// login-test.spec.js
import
{
test
,
expect
}
from
'@playwright/test'
;
test
(
'User logs in and verifies the result'
,
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 navigation and check the title
await expect
(
page
)
.
toHaveTitle
(
/Dashboard/
)
;
// 5. Verify the welcome text
await expect
(
page.
locator
(
'.welcome'
)
)
.
toHaveText
(
'Welcome, testuser'
)
;
// 6. Check the button state
await expect
(
page.
locator
(
'#logout'
)
)
.
toBeVisible
(
)
;
await expect
(
page.
locator
(
'#logout'
)
)
.
toBeEnabled
(
)
;
// 7. Get the 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 test)
expect
(
await page.
screenshot
(
)
)
.
toMatchSnapshot
(
'dashboard.png'
)
;
}
)
;
This test verifies:
- Whether the page title and welcome text are correct
- Whether elements are visible / enabled
- Whether user information attributes exist
- Page screenshots and UI snapshot comparison
Common API Tables
Below is a data extraction and validationrelated API reference 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 an element | await page.$eval('#logo', el => el.tagName) |
page.$$eval(selector, fn) |
Execute functions in bulk | 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 hidden | expect(page.locator('#loading')).toBeHidden() |
expect(locator).toBeEnabled() |
Element enabled | expect(page.locator('#submit')).toBeEnabled() |
expect(locator).toBeDisabled() |
Element disabled | expect(page.locator('#submit')).toBeDisabled() |
expect(locator).toBeChecked() |
Element 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') |