← Back to Tutorials

4. Basic Methods

Locators

// By text
await page.getByText('Login').click();

// By CSS selector
await page.locator('#submit-btn').click();

// By placeholder
await page.getByPlaceholder('Enter email').fill('test@example.com');

// By test ID (recommended)
await page.getByTestId('checkout-button').click();

Text Extraction

// Get text content
const heading = await page.textContent('h1');
const allText = await page.locator('.item').allTextContents();

// Get input value
const email = await page.inputValue('#email');

// Get attribute
const href = await page.getAttribute('a', 'href');

Waits & Auto-Waiting

Playwright auto-waits for elements to be actionable before clicking. You can also use explicit waits:

// Auto-waiting (built-in)
await page.getByText('Submit').click();  // waits for visible, enabled, stable

// Explicit waits
await page.waitForSelector('.loading-spinner', { state: 'hidden' });
await page.waitForURL('**/dashboard');
await page.waitForTimeout(2000);  // not recommended

Practice Apps

// Example: Login to SauceDemo
test('login', async ({ page }) => {
  await page.goto('https://www.saucedemo.com');
  await page.fill('#user-name', 'standard_user');
  await page.fill('#password', 'secret_sauce');
  await page.click('#login-button');
  await expect(page.locator('.inventory_list')).toBeVisible();
});
✏️ Exercise: Write a test that opens SauceDemo, logs in, extracts the text of all product names, and asserts there are 6 products.