Playwright Page Operation Basics
This chapter, we will learn how Playwright interacts with web pages in practice and the most commonly used page operation APIs.\\n\\n* * *\\n\\n## Page Navigation\\n\\nPage navigation is the most common operation. Playwright provides multiple APIs to open, refresh, and control page redirects.\\n\\n### 1. Open a Web Page (`page.goto`)\\n\\n```javascript\\nawait page.goto('https://example.com');\\n\\nCommon parameters:\\n\\n* `url`: The address to visit\\n* `timeout`: Timeout duration, default is 30 seconds\\n* `waitUntil`: Condition to wait for page loading\\n\\n * `'load'`: Wait for the `load` event (page and resources fully loaded)\\n * `'domcontentloaded'`: Wait for DOM content to be loaded\\n * `'networkidle'`: Wait for network to be idle\\n\\n## Example\\n\\n```javascript\\nawait page.goto('https://example.com',{ waitUntil:'domcontentloaded'});\\n\\n### 2. Page Refresh (`page.reload`)\\n\\nRefresh the current page.\\n\\n```javascript\\nawait page.reload({ waitUntil: 'networkidle' });\\n\\n### 3. Forward / Backward (`page.goBack` / `page.goForward`)\\n\\nSimulate the browser's forward and backward buttons.\\n\\n```javascript\\nawait page.goto('https://example.com'); await page.goto('https://playwright.dev'); await page.goBack(); // Returns to example.com await page.goForward(); // Forwards to playwright.dev\\n\\n### 4. Wait for Page Load\\n\\nSometimes you need to explicitly wait for an element to load on the page. Playwright provides an intelligent waiting mechanism.\\n\\n```javascript\\nawait page.waitForLoadState('networkidle'); // Wait for network to be idle await page.waitForSelector('#main-content'); // Wait for element to appear\\n\\n* * *\\n\\n## Element Locators\\n\\nTo interact with a page, you first need to locate the target element. Playwright provides multiple selectors.\\n\\n### 1. CSS Selectors\\n\\nThe most commonly used positioning method, consistent with front-end development.\\n\\n```javascript\\nawait page.click('#login-button'); // By id await page.click('.btn-primary'); // By class await page.click('form > button'); // By hierarchy\\n\\n### 2. XPath Selectors\\n\\nLocate elements through XPath expressions.\\n\\n```javascript\\nawait page.click('//button[text()="Login"]'); await page.click('//input[@name="username"]');\\n\\nXPath is more flexible but less readable, not recommended as the first choice.\\n\\n### 3. Text Content Locator\\n\\nLocate elements through their visible text.\\n\\n```javascript\\nawait page.click('text=Login'); await page.click('button:has-text("submit")');\\n\\n### 4. Attribute Locator\\n\\nUse attributes directly for selection.\\n\\n```javascript\\nawait page.fill('input', 'test@example.com'); await page.click('');\\n\\n### 5. Best Practices for Locator Strategies\\n\\n* **Prioritize unique and stable selectors** (such as `data-testid`, `data-test` attributes)\\n* Avoid relying on dynamic id or class names\\n* Use **`page.getByRole`**, **`page.getByText`** and other more readable methods (recommended in Playwright 5.x)\\n\\n## Example\\n\\n```javascript\\nawait page.getByRole('button',{ name:'submit'}).click();\\n\\n await page.getByPlaceholder('Please enter username').fill('admin');\\n\\n* * *\\n\\n## Basic Interactions\\n\\nPlaywright supports multiple ways to interact with elements, including clicking, inputting, keyboard, and mouse operations.\\n\\n### 1. Click Operation (`page.click`)\\n\\n```javascript\\nawait page.click('#submit');\\n\\nOptional parameters:\\n\\n* `button`: `'left' | 'right' | 'middle'` (default is left)\\n* `clickCount`: Number of clicks (set to 2 for double-click)\\n* `modifiers`: Keyboard combination keys (such as `['Control']`)\\n\\n## Example\\n\\n```javascript\\nawait page.click('#submit',{ button:'right'});// Right-click\\n\\n await page.dblclick('#submit');// Double-click\\n\\n### 2. Input Text (`fill` vs `type`)\\n\\n* `fill(selector, value)`: Clear the input field and enter a new value (recommended for most cases)\\n* `type(selector, text)`: Simulate typing character by character (with delay, closer to real user behavior)\\n\\n## Example\\n\\n```javascript\\nawait page.fill('input','test_user');\\n\\n await page.type('input','playwright',{ delay:200});\\n\\n### 3. Keyboard Operations\\n\\n* `press`: Simulate key press\\n* `keyboard.type`: Continuously input text\\n* `keyboard.press`: Press a specific key (can include combination keys)\\n\\n## Example\\n\\n```javascript\\nawait page.press('input','Enter');\\n\\n await page.keyboard.type('Hello World!');\\n\\n await page.keyboard.press('Control+A');// Select all\\n\\n await page.keyboard.press('Backspace');// Delete\\n\\n### 4. Mouse Operations\\n\\nPlaywright provides complete mouse control:\\n\\n* `hover`: Mouse hover\\n* `mouse.move(x, y)`: Move to coordinates\\n* `mouse.click(x, y)`: Click at coordinates\\n* `mouse.down / mouse.up`: Press/release mouse button\\n* `dragAndDrop`: Drag and drop elements (Playwright 1.18+)\\n\\n## Example\\n\\n```javascript\\nawait page.hover('#menu');// Hover\\n\\n await page.mouse.move(100,200);// Move to coordinates\\n\\n await page.mouse.click(120,220);// Click at coordinates\\n\\n await page.dragAndDrop('#item1','#dropzone');// Drag to target area\\n\\n* * *\\n\\n## Complete Example: Simulate Login and Take Screenshot\\n\\nBelow is a complete Playwright script demonstrating navigation, locators, input, clicking, and other basic operations.\\n\\n## Example\\n\\n```javascript\\nconst{ chromium }= require('playwright');\\n\\n(async ()=>{\\n\\n// 1. Launch browser and create a new page\\n\\nconst browser = await chromium.launch({ headless:false});\\nconst page = await browser.newPage();\\n\\n// 2. Navigate to login page\\n\\n await page.goto('https://github.com/login');\\n console.log(`Current page titleοΌ${await page.title()}`);\\n\\n// 3. Element locator and input\\n\\n// Locate username input field and enter username\\n\\n await page.locator('#login_field').fill('your_username');\\n\\n// Locate password input field and enter password\\n\\n await page.locator('#password').fill('your_password');\\n\\n// 4. Click login button\\n\\n// Using .getByRole() is a more robust locator method\\n\\n await page.getByRole('button',{ name:'Sign in'}).click();\\n\\n// 5. Wait for page navigation to complete, ensure login is successful\\n\\n await page.waitForURL('https://github.com/');\\n\\n// 6. Take screenshot to confirm login status\\n\\n await page.screenshot({ path:'github_homepage.png'});\\n console.log('Login successful, screenshot taken');\\n\\n// 7. Close browser\\n\\n await browser.close();\\n\\n})();\\n\\nHow to run:\\n\\n* Save the code as github_login.js in your project directory.\\n* Execute `node github_login.js` in the terminal.\\n\\n* * *\\n\\n## Common API Summary Table\\n\\n| Category | Method / Property | Description |\\n| --- | --- | --- |\\n| Page Navigation | `page.goto(url[, options])` | Open page |\\n| | `page.reload()` | Refresh page |\\n| | `page.goBack()` | Go back |\\n| | `page.goForward()` | Go forward |\\n| | `page.waitForLoadState()` | Wait for page load state |\\n| Element Locators | `page.locator(selector)` | General locator |\\n| | `page.getByRole(role, options)` | Locate by role |\\n| | `page.getByText(text)` | Locate by text |\\n| | `page.getByPlaceholder(text)` | Locate by placeholder |\\n| | `page.getByLabel(text)` | Locate by label |\\n| Basic Interactions | `page.click(selector[, options])` | Click element |\\n| | `page.dblclick(selector)` | Double-click |\\n| | `page.fill(selector, value)` | Input text (clear then fill) |\\n| | `page.type(selector, text[, options])` | Simulate typing character by character |\\n| | `page.press(selector, key)` | Press key on element |\\n| | `page.keyboard.type(text)` | Keyboard input |\\n| | `page.keyboard.press(key)` | Keyboard key press (including combination keys) |\\n| | `page.hover(selector)` | Hover |\\n| | `page.mouse.move(x, y)` | Move mouse |\\n| | `page.mouse.click(x, y[, options])` | Click at coordinates |\\n| | `page.dragAndDrop(src, dest)` | Drag and drop element |
YouTip