Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Playwright Advanced Page Actions

Playwright Advanced Page Actions

In this chapter we will introduce Playwright advanced page actions, which are closer to real testing needs and cover waiting mechanisms, form handling, and pop-up dialogs and other advanced features.


Waiting mechanisms

One of Playwright's biggest advantages is smart waiting (auto-waiting): most actions (such as click, fill) automatically wait for elements to be visible and actionable. But in complex scenarios, you still need to control waiting manually.

1. Implicit waiting (Auto-waiting)

Playwright's built-in waiting mechanism:

Example

await page.

click

(

'#submit'

)

;

// Automatically wait for the button to be visible and clickable

2. Explicit waiting

Explicitly call waiting methods, such as waiting for a selector, text, or request.

Example

await page.

waitForSelector

(

'#result'

,

{

state

:

'visible'

}

)

;

Common state value:

3. Waiting for an element to appear / disappear

// 等待元素出现

await page.waitForSelector('#loading', { state: 'visible' });



// Wait for element to disappear

await page.waitForSelector('#loading', { state: 'hidden' });

4. Waiting for network requests to complete

Waiting for a request to complete, commonly used for AJAX requests or API calls.

// 等待指定 URL 的请求完成

await page.waitForResponse(response => 

  response.url().includes('/api/login') && response.status() === 200

);

5. Custom waiting conditions

Pass page.waitForFunction Execute custom waiting logic.

// 等待页面上计数器达到 10

await page.waitForFunction(() => {

  return document.querySelector('#count').innerText === '10';

});


Form handling

Forms are the most common interaction scenario in testing. Playwright provides a rich set of APIs to manipulate form controls.

1. Input box operations

await page.fill('#username', 'admin');  // 清空并输入

await page.type('#search', 'Playwright', { delay: 100 }); // 模拟逐字输入

2. Dropdown menu selection

// 通过 value

await page.selectOption('#country', 'china');



// By tag text

await page.selectOption('#country', { label: 'United States' });



// via index

await page.selectOption('#country', { index: 2 });

3. Checkboxes and radio buttons

// 勾选复选框

await page.check('#agree');



// Uncheck

await page.uncheck('#subscribe');



// Click radio button

await page.check('input[type="radio"][value="male"]');

4. File upload

// 直接上传文件

await page.setInputFiles('#upload', 'example.png');



// Upload multiple files

await page.setInputFiles('#upload', ['a.png', 'b.png']);



// Clear file

await page.setInputFiles('#upload', []);

5. Form submission

There are two ways to submit a form:

await page.click('button[type="submit"]');

// 或者

await page.press('#form input[name="email"]', 'Enter');


Pop-ups and dialogs

Playwright can capture and handle native browser pop-ups(alert, confirm, prompt), as well as custom modals.

1. Alert handling

page.once('dialog', async dialog => {

  console.log(dialog.message()); // 打印弹窗内容

  await dialog.accept(); // 点击 "确定"

});



await page.click('#show-alert');

2. Confirm handling

page.once('dialog', async dialog => {

  console.log(dialog.message());

  await dialog.dismiss(); // 点击 "取消"

});



await page.click('#show-confirm');

3. Prompt handling

page.once('dialog', async dialog => {

  console.log(dialog.message());

  await dialog.accept('Playwright'); // 输入内容并确认

});



await page.click('#show-prompt');

4. Custom modals

Custom modals (such as Bootstrap / Ant Design) are actually ordinary DOM elements and can be handled directly with locator + interaction to close or enter input.

await page.click('#open-modal');

await page.fill('.modal input[name="name"]', 'Test User');

await page.click('.modal button.confirm');


Practical case — automated testing of a registration form

The following example comprehensively uses waiting mechanisms, form actions, file upload, and dialog handling。

Example

// register-test.js

const

{

chromium

}

=

require

(

'playwright'

)

;

(

async

(

)

=>

{

 

const

browser

=

await chromium.

launch

(

{

headless

:

false

,

slowMo

:

500

}

)

;

 

const

context

=

await browser.

newContext

(

)

;

 

const

page

=

await context.

newPage

(

)

;

 

// 1. Open the registration page

  await page.

goto

(

'https://example.com/register'

,

{

waitUntil

:

'domcontentloaded'

}

)

;

 

// 2. Wait for the form to appear

  await page.

waitForSelector

(

'#register-form'

,

{

state

:

'visible'

}

)

;

 

// 3. Enter basic information

  await page.

fill

(

'#username'

,

'testuser'

)

;

  await page.

fill

(

'#email'

,

'test@example.com'

)

;

  await page.

fill

(

'#password'

,

'Password123'

)

;

 

// 4. Select the country from a dropdown

  await page.

selectOption

(

'#country'

,

{

label

:

'China'

}

)

;

 

// 5. Check the terms

  await page.

check

(

'#agree'

)

;

 

// 6. Upload the avatar

  await page.

setInputFiles

(

'#avatar'

,

'avatar.png'

)

;

 

// 7. Click Submit

  page.

once

(

'dialog'

,

async dialog

=>

{

    console.

log

(

'Popup content:'

,

dialog.

message

(

)

)

;

    await dialog.

accept

(

)

;

// Click OK

 

}

)

;

  await page.

click

(

'button[type="submit"]'

)

;

 

// 8. Wait for the redirect after submission completes

  await page.

waitForLoadState

(

'networkidle'

)

;

 

// 9. Assert the result (whether it contains the welcome text)

 

const

successText

=

await page.

textContent

(

'.welcome-message'

)

;

  console.

log

(

'Registration result:'

,

successText

)

;

 

// 10. Save screenshot

  await page.

screenshot

(

{

path

:

'register-success.png'

}

)

;

  await browser.

close

(

)

;

}

)

(

)

;

Effect after running:


Complete API

The following is a summary of page navigation, waiting, forms, interactions, and popups common APIs:

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, options]) Wait for load to complete
Waiting mechanisms page.waitForSelector(selector[, options]) Wait for an element to appear/disappear
page.waitForResponse(fn[, options]) Wait for a specific request response
page.waitForFunction(pageFn[, arg, options]) Custom wait conditions
Element locating page.locator(selector) Generic locators
page.getByRole(role, options) Locate by role
page.getByText(text) Locate by text
page.getByPlaceholder(text) Input box placeholder
page.getByLabel(text) Form label
Form operations page.fill(selector, value) Input box (clear then fill)
page.type(selector, text[, options]) Simulate typing character by character
page.press(selector, key) Press keys on an element
page.selectOption(selector, values) Dropdown selection
page.check(selector[, options]) Check checkbox/radio button
page.uncheck(selector[, options]) Uncheck
page.setInputFiles(selector, files) File upload
Basic interactions page.click(selector[, options]) Click an element
page.dblclick(selector[, options]) Double-click
page.hover(selector[, options]) Hover
page.mouse.move(x, y) Mouse move
page.mouse.click(x, y[, options]) Mouse click
page.dragAndDrop(src, dest[, options]) Drag element
Dialog handling page.on('dialog', handler) Listen for dialog events
dialog.message() Get the pop-up text
dialog.accept([promptText]) Accept (with optional input)
dialog.dismiss() Cancellation
Screenshots and assertions page.screenshot({ path }) Save screenshot
page.textContent(selector) Get text content
expect(locator).toHaveText(text) Assert text (requires using @playwright/test)