First, let's locate the h1 element. We'll use the page.locator()
method and specify a CSS selector that matches our h1 element. Let's say our h1 element has an id of "title". Here's how you can locate it:
const titleElement = await page.locator('#title');
Next, we'll get the text content of the h1 element using the locator.textContent()
method. This method returns a Promise that resolves to a string containing all of the text within the h1 element.
const titleText = await titleElement.textContent();
Now, let's check if this text contains "hello, world". We'll use JavaScript's String.prototype.includes()
method. This method returns true if the specified substring is found within the string.
if (titleText.includes('hello, world')) {
console.log('The title contains "hello, world"!');
} else {
console.log('The title does not contain "hello, world".');
}
And that's it! You've just checked if an h1 element includes a specific string using Playwright. Remember, the steps are:
page.locator()
.locator.textContent()
.String.prototype.includes()
to check for your desired substring.For more tips and tricks on using Playwright, check out our blog post on Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].