Playwright Page Interaction Basics
In this section, we learn how Playwright interacts with web pages and the most commonly used page operation APIs.
Page navigation
Page navigation is the most common operation; Playwright provides multiple APIs to open, refresh, and control page navigation.
1. Open a web page (page.goto)
await page.goto('https://example.com');
Common parameters:
url: the address to visittimeout: timeout, default 30 seconds-
waitUntil: condition to wait for page load 'load': wait forloadevent (page and all resources fully loaded)'domcontentloaded': wait for DOM content to load'networkidle': wait for network idle
Example
await page.
goto
(
'https://example.com'
,
{
waitUntil
:
'domcontentloaded'
}
)
;
2. Refresh page (page.reload)
Refresh the current page.
await page.reload({ waitUntil: 'networkidle' });
3. Forward / Back (page.goBack / page.goForward)
Simulate the browser's forward and back buttons.
await page.goto('https://example.com');
await page.goto('https://playwright.dev');
await page.goBack(); // 返回 example.com
await page.goForward(); // 前进到 playwright.dev
4. Wait for page load
Sometimes you need to explicitly wait for an element to load; Playwright provides an intelligent waiting mechanism.
await page.waitForLoadState('networkidle'); // 等待网络空闲
await page.waitForSelector('#main-content'); // 等待元素出现
Element locating
To interact with a page, you first need to locate the target element. Playwright provides multiple selectors.
1. CSS selector
The most common locating method, consistent with front-end development.
await page.click('#login-button'); // 通过 id
await page.click('.btn-primary'); // 通过 class
await page.click('form > button'); // 通过层级关系
2. XPath selector
Locate elements via XPath expressions.
await page.click('//button[text()="登录"]');
await page.click('//input[@name="username"]');
XPath is more flexible but less readable, and is not recommended as the first choice.
3. Text content locating
Locate via an element's visible text.
await page.click('text=登录');
await page.click('button:has-text("提交")');
4. Attribute locating
Select directly using attributes.
await page.fill('input[name="email"]', 'test@example.com');
await page.click('[data-test="submit-button"]');
5. Best practices for locating strategies
- Prefer unique and stable selectors(such as
data-testid、data-testproperty) - Avoid relying on dynamic id or class names
- Use
page.getByRole、page.getByTextand other more readable methods (recommended in Playwright 5.x)
Example
await page.
getByRole
(
'button'
,
{
name
:
'Submit'
}
)
.
click
(
)
;
await page.
getByPlaceholder
(
'Please enter username'
)
.
fill
(
'admin'
)
;
Basic interactions
Playwright supports multiple ways to interact with elements, covering clicks, input, keyboard, and mouse operations.
1. Click operation (page.click)
await page.click('#submit');
Optional parameters:
button:'left' | 'right' | 'middle'(default left button)clickCount: number of clicks (set to 2 for double-click)modifiers: keyboard modifier keys (such as['Control'])
Example
await page.
click
(
'#submit'
,
{
button
:
'right'
}
)
;
// Right-click
await page.
dblclick
(
'#submit'
)
;
// Double-click
2. Input text (fill vs type)
fill(selector, value): clear the input and enter a new value (recommended, used in most cases)type(selector, text): simulate typing character by character (with delay, closer to a real user)
Example
await page.
fill
(
'input[name="username"]'
,
'test_user'
)
;
await page.
type
(
'input[name="search"]'
,
'playwright'
,
{
delay
:
200
}
)
;
3. Keyboard operations
press: simulate key presskeyboard.type: input text continuouslykeyboard.press: press a key (can include modifiers)
Example
await page.
press
(
'input[name="username"]'
,
'Enter'
)
;
await page.
keyboard
.
type
(
'Hello World!'
)
;
await page.
keyboard
.
press
(
'Control+A'
)
;
// Select all
await page.
keyboard
.
press
(
'Backspace'
)
;
// Delete
4. Mouse operations
Playwright provides complete mouse control:
hover: mouse hovermouse.move(x, y): move to coordinatesmouse.click(x, y): click at coordinatesmouse.down / mouse.up: press/release mouse buttondragAndDrop: drag element (Playwright 1.18+)
Example
await page.
hover
(
'#menu'
)
;
// Hover
await page.
mouse
.
move
(
100
,
200
)
;
// Move to coordinates
await page.
mouse
.
click
(
120
,
220
)
;
// Click at coordinates
await page.
dragAndDrop
(
'#item1'
,
'#dropzone'
)
;
// Drag to target area
Complete example: Simulate login and take a screenshot
Below is a complete Playwright script demonstrating basic operations such as navigation, locating, input, and clicking.
Example
const
{
chromium
}
=
require
(
'playwright'
)
;
(
async
(
)
=>
{
// 1. Launch the browser and create a new page
const
browser
=
await chromium.
launch
(
{
headless
:
false
}
)
;
const
page
=
await browser.
newPage
(
)
;
// 2. Navigate to the login page
await page.
goto
(
'https://github.com/login'
)
;
console.
log
(
`Current page title: $
{
await page.
title
(
)
}
`
)
;
// 3. Element locating and input
// Locate the username input and enter the username
await page.
locator
(
'#login_field'
)
.
fill
(
'your_username'
)
;
// Locate the password input and enter the password
await page.
locator
(
'#password'
)
.
fill
(
'your_password'
)
;
// 4. Click the login button
// Using .getByRole() is a more robust locating method
await page.
getByRole
(
'button'
,
{
name
:
'Sign in'
}
)
.
click
(
)
;
// 5. Wait for page navigation to complete to ensure successful login
await page.
waitForURL
(
'https://github.com/'
)
;
// 6. Save a screenshot to confirm login status
await page.
screenshot
(
{
path
:
'github_homepage.png'
}
)
;
console.
log
(
'Login successful, screenshot saved'
)
;
// 7. Close the browser
await browser.
close
(
)
;
}
)
(
)
;
How to run:
- Save the code as github_login.js in the project directory.
- Run node github_login.js in the terminal.
Common API summary table
| Classification | Method / Property | Description |
|---|---|---|
| Page navigation | page.goto(url[, options]) |
Open the page |
page.reload([options]) |
Refresh the page | |
page.goBack([options]) |
Backspace | |
page.goForward([options]) |
Go forward | |
page.waitForLoadState([state]) |
Wait for page load state | |
| Element locating | page.locator(selector) |
Generic locators |
page.getByRole(role, options) |
Locate by role | |
page.getByText(text) |
Locate by text | |
page.getByPlaceholder(text) |
Locate by placeholder | |
page.getByLabel(text) |
Locate by label | |
| Basic interactions | page.click(selector[, options]) |
Click an element |
page.dblclick(selector) |
Double-click | |
page.fill(selector, value) |
Input text (clear then fill) | |
page.type(selector, text[, options]) |
Simulate typing character by character | |
page.press(selector, key) |
Press keys on an element | |
page.keyboard.type(text) |
Keyboard input | |
page.keyboard.press(key) |
Keyboard key press (including modifiers) | |
page.hover(selector) |
Hover | |
page.mouse.move(x, y) |
Move mouse | |
page.mouse.click(x, y[, options]) |
Click at coordinates | |
page.dragAndDrop(src, dest) |
Drag element |