Welcome back! You've already learned how to navigate web pages, perform click actions, and fill out and submit forms using Playwright in a TypeScript environment. Great job so far! Now we’re going to look at another crucial aspect of web automation: extracting page content.
Extracting information from web pages is vital for tasks like validating elements, scraping data, and dynamically checking web page content. By the end of this lesson, you'll be comfortable with capturing text content from web pages, an essential skill for various web automation and testing scenarios.
In this lesson, you will master extracting text content from a web page.
Here's the code example we'll be working with:
TypeScript1import { test, expect } from '@playwright/test'; 2 3test('extract text content', async ({ page }) => { 4 await page.goto('http://localhost:3000'); 5 const mainHeader = await page.textContent('h1'); 6 expect(mainHeader).toBe('Welcome to the BookStore'); 7});
In this code, we navigate to http://localhost:3000
, use the page.textContent
method to extract the text content of an <h1>
element, and assert that the text matches the expected value, "Welcome to the BookStore."
Extracting page content is essential for verifying that web applications display the correct information. Think of it as a way to make sure that what the user sees matches what you expect. This is crucial for testing static and dynamic content, ensuring that pages load correctly, and validating that user actions result in the expected changes on the page.
Imagine you are testing an e-commerce website and need to ensure that the product names, prices, and descriptions are all correctly displayed. By mastering the skill of extracting and validating page content, you can automate these checks and catch issues early before they affect users.
Exciting, right? Let's move on to the practice section and put these concepts into action. Your journey to becoming a web automation expert continues here!