Skip to content

Core API Reference

The hallmark of Playwright is "Smart by Default, Reduced Noise"—much of the wait logic you had to write manually in Selenium is handled automatically. This chapter explains the most commonly used APIs in plain language, with side-by-side JS and Python examples.


1. Page Navigation

javascript
// JavaScript
await page.goto('https://example.com');
await page.goto('https://example.com', { waitUntil: 'networkidle' });
python
# Python
page.goto("https://example.com")
page.goto("https://example.com", wait_until="networkidle")

waitUntil Parameter Description:

ValueMeaningRecommended Scenario
'commit'Considered complete upon receiving server response headers.Rarely used.
'domcontentloaded'DOM tree is built.Fast navigation; no reliance on images.
'load'All resources (images, CSS) are loaded.Medium complexity (Default).
'networkidle'No network activity for at least 500ms.SPA websites; full load.

Other Navigation Methods:

javascript
await page.goBack();     // Back
await page.goForward();  // Forward
await page.reload();     // Refresh

2. Locator: Positioning Elements (Playwright Core Advantage)

IMPORTANT

Playwright's Locator is a revolutionary improvement over the old-fashioned find_element:

  • Auto-waiting: Automatically waits for the element to appear, become visible, and be clickable.
  • Auto-retry: If an operation fails (e.g., element is blocked), it retries automatically.
  • Semantic Searching: Search by role, label, text, or placeholder; less reliant on fragile CSS selectors.

Common Positioning Methods

javascript
// JavaScript —— Recommended priority from high to low

// 1. By Role (Highly recommended; clear semantics)
page.getByRole('button', { name: 'Log In' })
page.getByRole('textbox', { name: 'Account' })
page.getByRole('link', { name: 'Register' })

// 2. By Text Content
page.getByText('Buy Now')
page.getByText('Buy Now', { exact: true })  // Exact match

// 3. By Placeholder (Input prompt text)
page.getByPlaceholder('Enter phone number')

// 4. By Label Text (Excellent for form scenarios)
page.getByLabel('Email Address')

// 5. By CSS Selector (Traditional fallback)
page.locator('#username')
page.locator('.btn-primary')
page.locator('button[type="submit"]')

// 6. By XPath
page.locator('//input[@name="password"]')
python
# Python (Method names identical, camelCase → snake_case)
page.get_by_role("button", name="Log In")
page.get_by_text("Buy Now")
page.get_by_placeholder("Enter phone number")
page.get_by_label("Email Address")
page.locator("#username")

Finding Multiple Elements (Returns a Locator List)

javascript
// Get all matching elements
const items = page.locator('.product-item');
const count = await items.count();         // Total count
const first = items.first();              // First one
const last  = items.last();               // Last one
const third = items.nth(2);              // Third one (starting from 0)

// Filtering (Powerful filter method)
const buttons = page.getByRole('button');
await buttons.filter({ hasText: 'Buy' }).click();  // Click only buttons containing "Buy" text

3. Auto-waiting Mechanism (Say Goodbye to sleep)

Playwright's Locator operations (click, fill, type, etc.) automatically wait for the element to meet these conditions before execution:

  • Element exists in DOM.
  • Element is visible (not hidden).
  • Element is stable (not moving during animation).
  • Element is clickable (not blocked).
javascript
// Just click; Playwright waits for it to be clickable.
await page.getByRole('button', { name: 'Submit' }).click();
// Equivalent in Selenium:
// wait.until(EC.element_to_be_clickable(...)); element.click();

Manual Waiting (Special Cases Only)

javascript
// Wait for a specific selector to appear
await page.waitForSelector('.success-message');

// Wait for URL change
await page.waitForURL('**/dashboard');

// Wait for a function to return true
await page.waitForFunction(() => document.querySelector('#result')?.textContent === 'Done');

// Wait for network response (Commonly used after button click triggers API)
const [response] = await Promise.all([
  page.waitForResponse(resp => resp.url().includes('/api/login')),
  page.getByRole('button', { name: 'Log In' }).click()
]);
const data = await response.json();

4. Form Operations

javascript
// Input text (Clears then fills)
await page.getByLabel('Email').fill('user@example.com');

// Simulate real human typing (Character by character)
await page.getByLabel('Password').pressSequentially('MyPassword123', { delay: 80 });

// Clear input field
await page.getByPlaceholder('Search').clear();

// Check/Uncheck checkboxes
await page.getByRole('checkbox', { name: 'Remember Me' }).check();
await page.getByRole('checkbox', { name: 'Remember Me' }).uncheck();

// Dropdown selection
await page.getByRole('combobox', { name: 'Country' }).selectOption('CN');
await page.getByRole('combobox').selectOption({ label: 'China' });   // Select by text

// File upload
await page.getByLabel('Upload').setInputFiles('path/to/file.jpg');

5. Keyboard and Mouse Operations

javascript
// Keyboard keys (Common shortcuts)
await page.keyboard.press('Enter');
await page.keyboard.press('Control+A');    // Select all
await page.keyboard.press('Control+C');    // Copy
await page.keyboard.press('Escape');

// Mouse operations
await page.mouse.move(100, 200);           // Move mouse
await page.mouse.click(100, 200);         // Click at coordinate
await page.mouse.dblclick(100, 200);      // Double click
await page.mouse.wheel(0, 300);           // Scroll down 300px

// Hover (Trigger hover menus)
await page.getByRole('menuitem', { name: 'More' }).hover();

6. Retrieving Element Info

javascript
// Get text content
const text = await page.getByRole('heading').innerText();

// Get attribute values
const href = await page.locator('a.link').getAttribute('href');
const val  = await page.locator('input#amount').inputValue();  // Input value

// Determine status
const isVisible = await page.locator('#modal').isVisible();
const isEnabled = await page.getByRole('button').isEnabled();
const isChecked = await page.getByRole('checkbox').isChecked();

7. Network Interception & Mocking (Unique Advantage)

One of Playwright's most powerful features: Intercepting and modifying requests before they leave the browser.

Intercept and Mock API Responses

javascript
// Intercept specific API request and return mock data
await page.route('**/api/user/info', async route => {
  await route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify({ name: 'Mbbrowser Test User', vip: true })
  });
});

Wait for Specific Request Completion

javascript
// Scenario: After clicking "Load More", wait for the data API to return before reading content.
const [response] = await Promise.all([
  page.waitForResponse(resp => resp.url().includes('/api/products') && resp.status() === 200),
  page.getByRole('button', { name: 'Load More' }).click()
]);
const products = await response.json();
console.log(`Retrieved ${products.length} products`);

Block Ads/Unnecessary Resources (Speed up pages)

javascript
await page.route('**/*.{png,jpg,gif,webp,svg}', route => route.abort()); // Block images
await page.route('**/{ads,analytics,tracker}**', route => route.abort()); // Block ads

javascript
// Get all Cookies
const cookies = await context.cookies();
console.log(cookies);

// Inject Cookies (Best before opening web pages)
await context.addCookies([
  { name: 'token', value: 'abc123', domain: '.example.com', path: '/' }
]);

// Clear all Cookies
await context.clearCookies();

9. Multi-Tab Operations

javascript
// Listen for new tab opening events
const [newPage] = await Promise.all([
  context.waitForEvent('page'),            // Wait for new tab to appear
  page.getByRole('link').click()           // Trigger operation that opens new tab
]);
await newPage.waitForLoadState();
console.log('New tab title:', await newPage.title());

// Get all opened tabs
const allPages = context.pages();
console.log(`Total tabs: ${allPages.length}`);

// Manually open a new tab
const anotherPage = await context.newPage();
await anotherPage.goto('https://www.google.com');

10. iframe Operations

javascript
// Locate iframe and interact within it
const iframe = page.frameLocator('iframe#loginFrame');
await iframe.getByLabel('Username').fill('my_user');
await iframe.getByRole('button', { name: 'Log In' }).click();

11. Screenshots and PDF

javascript
// Take full screen screenshot
await page.screenshot({ path: 'screenshot.png' });

// Take full page screenshot (includes scrollable content)
await page.screenshot({ path: 'full-page.png', fullPage: true });

// Screenshot specific element
await page.locator('#product-card').screenshot({ path: 'product.png' });

// Generate PDF (Chromium only)
await page.pdf({ path: 'report.pdf', format: 'A4' });

12. Executing JavaScript

javascript
// Execute JS inside the page and get return value
const title = await page.evaluate(() => document.title);

// Pass parameters to page-side JS
const itemCount = await page.evaluate(
  selector => document.querySelectorAll(selector).length,
  '.product-item'
);

// DOM Manipulation: Force click a blocked element
await page.evaluate(selector => {
  document.querySelector(selector).click();
}, '#hidden-btn');

TIP

Mastered the APIs? The next chapter Real-world Example Library provides five complete templates you can directly reuse: login, scraping, network interception, concurrency... copy and use!