YouTip LogoYouTip

Playwright First Script

Before writing code, it is crucial to understand the core concepts of Playwright. The three most core objects are Browser, BrowserContext, and Page. These three objects form the foundation of your interaction with web pages:\n\n* **Browser**: This is the starting point of the automation process. A `Browser` instance represents an actual browser, such as Chromium, Firefox, or WebKit. You can launch a browser and then create multiple independent sessions within it.\n\n* **BrowserContext**: A `BrowserContext` is like an independent browser session. It completely isolates data such as pages, local storage, and cookies. This allows you to run multiple independent automation tasks simultaneously in one browser, just like opening multiple tabs in incognito mode.\n\n* **Page**: The `Page` is where you perform actual operations. It represents a tab or window in a browser context. All operations, such as clicking, typing, navigating, taking screenshots, etc., are executed on the `Page` object.\n\n!(#)\n\n**Relationship between the three:**\n\nA **Browser** can contain multiple **BrowserContexts**, and a **BrowserContext** can contain multiple **Pages**. Typically, we only need one `Browser` and one `BrowserContext`, but in scenarios that require data isolation, `BrowserContext` becomes very useful.\n\n* * *\n\n## Writing Your First Script\n\nNext, we will write a simple script that launches the browser, visits Baidu, and then takes a screenshot.\n\nCreate a file named `baidu_script.js` and paste the following code:\n\n## Instance\n\nconst{ chromium }= require('playwright');\n\n(async ()=>{\n\n// Launch the browser and create a new browser context.\n\nconst browser = await chromium.launch({ headless:false});// headless: false The browser window will be displayed.\n\nconst context = await browser.newContext();\n\nconst page = await context.newPage();\n\n// Navigate to the website you want to visit.\n\n await page.goto('https://www.baidu.com');\n\n// Enter text into the search box.\n\n await page.fill('#kw','Playwright');\n\n// Press Enter or click the search button.\n\n await page.press('#kw','Enter');\n\n// Wait for navigation to complete, which is important to ensure the page has finished loading.\n\n await page.waitForNavigation();\n\n// Take a screenshot and save it.\n\n await page.screenshot({ path:'baidu_search_results.png'});\n\n// Print the title of the current page.\n\n console.log(`The page title is: ${await page.title()}`);\n\n// Close the browser.\n\n await browser.close();\n\n})();\n\n**Code Explanation:**\n\n* `const { chromium } = require('playwright');`: Imports the `chromium` module from the Playwright library. You can replace it with `firefox` or `webkit` as needed.\n* `await chromium.launch({ headless: false });`: Launches a Chromium browser instance. `headless: false` is a key option that will **display the browser window**, allowing you to see the script's execution process.\n* `await browser.newContext();` and `await context.newPage();`: The combination of these lines of code opens a new browser tab.\n* `await page.goto('https://www.baidu.com');`: **Navigates** to the specified URL. This is one of the most commonly used methods.\n* `await page.screenshot({ path: 'baidu_homepage.png' });`: Takes a screenshot of the current page and saves it to a file.\n* `await browser.close();`: **Closes** the browser and releases system resources.\n\n### Running the Script\n\nOpen a terminal or command prompt, navigate to your project directory, and execute the following command:\n\nnode baidu_script.js\nAfter execution, you will see a browser window automatically open, load the Baidu homepage, and then the window will close. In your project folder, a screenshot file named `baidu_homepage.png` will be generated.\n\n### Debug Mode\n\nWhen writing more complex scripts, you may need to debug.\n\nPlaywright provides a powerful debugging tool. We simply need to add `PWDEBUG=1` before the command line when running the script:\n\nPWDEBUG=1 node baidu_script.js\nAfter running, you will see a Playwright debug window where you can step through the code, inspect page elements, and see every step of the script's operation in real-time. This is very helpful for locating issues.\n\n### Viewing the Results\n\nIn addition to command-line output and screenshot files, you can also check the script's execution results in the following ways:\n\n* **console.log()**: Adding `console.log()` statements in the script can print variable values or confirm whether a specific step has been executed.\n* **Screenshots**: Using the `page.screenshot()` feature to save screenshots at key steps allows you to visually see the state of the page.\n* **File Operations**: You can write the scraped data to a local file for subsequent analysis.
← Playwright Advanced Page OperaPlaywright Install β†’