Playwright Page Operations Basics
In this chapter, we will 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 webpage (page.goto)
await page.goto('https://example.com');
Common parameters:
url: the address to visittimeout: timeout, default 30 seconds-
waitUntil: conditions for waiting for page load'load': wait forloadevent (page and resources fully loaded)'domcontentloaded': wait for DOM content to finish loading'networkidle': wait for network idle
Example
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 to load
Sometimes you need to explicitly wait for a certain element to load on the page. Playwright provides a smart 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 a variety of selectors.
1. CSS selectors
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 selectors
Locate elements via XPath expressions.
await page.click('//button[text()="登录"]');
await page.click('//input[@name="username"]');
XPath is more flexible, but less readable, so it is not recommended as the first choice.
3. Text content locating
Locate by the element's visible text.
await page.click('text=登录');
await page.click('button:has-text("提交")');
4. Attribute locating
Directly use attributes to select.
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-testattribute) - 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, including clicking, typing, keyboard, and mouse operations.
1. Click operations (page.click)
await page.click('#submit');
Optional parameters:
button:'left' | 'right' | 'middle'(left button by default)clickCount: number of clicks (set to 2 for double-click)modifiers: keyboard modifier keys (e.g.,['Control'])
Example
await page.dblclick('#submit'); // Double-click
2. Enter text (fill vs type)
fill(selector, value): clear the input field and enter a new value (recommended, used in most cases)type(selector, text): simulate character-by-character input (with delay, closer to real user behavior)
Example
await page.type('input[name="search"]', 'playwright', { delay: 200 });
3. Keyboard operations
press: simulate key presseskeyboard.type: type text continuouslykeyboard.press: press a key (can include modifier keys)
Example
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.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, typing, and clicking.
Example
(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 field and enter the username
await page.locator('#login_field').fill('your_username');
// Locate the password input field 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 login success
await page.waitForURL('https://github.com/');
// 6. Take a screenshot and save it to confirm the login status
await page.screenshot({ path: 'github_homepage.png' });
console.log('Login successful, screenshot taken');
// 7. Close the browser
await browser.close();
})();
How to run:
- Save the code in the project directory asgithub_login.js。
- Execute in the terminalnode github_login.js。
Common API Summary Table
| Category | Method / Property | Description |
|---|---|---|
| Page Navigation | page.goto(url[, options]) |
Open a page |
page.reload([options]) |
Refresh the page | |
page.goBack([options]) |
Back | |
page.goForward([options]) |
Forward | |
page.waitForLoadState([state]) |
Wait for page load state | |
| Element Locating | page.locator(selector) |
General-purpose locator |
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) |
Enter text (clear then fill) | |
page.type(selector, text[, options]) |
Simulate character-by-character typing | |
page.press(selector, key) |
Press a key on an element | |
page.keyboard.type(text) |
Keyboard typing | |
page.keyboard.press(key) |
Keyboard key press (including modifier combinations) | |
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 an element |