Getting text out of a web element sounds easy until you hit multiple matching elements, dynamic content, changing text or elements that go hidden or detached from the DOM.
Playwright gives you several ways to define locators: by CSS, text, role, testID, or XPath. But picking the right strategy matters to prevent the scope of flaky tests.
This guide covers Playwright’s getTextOfElement method to show you how text extraction is still reliable.
What is Playwright (and why text extraction still matters in 2026)?
Playwright is an open-source automation tool developed by Microsoft for end-to-end testing and browser automation. It enables developers and testers to control browser actions programmatically, supporting modern web applications and handling both static and dynamic content with ease.
Text extraction is fundamental in Playwright for several reasons:
- UI Validation: Ensuring that the correct text appears in the UI is a key part of automated UI testing.
- Data Extraction: Playwright enables you to scrape dynamic web pages and extract valuable data such as product details, news articles, or pricing information.
- Content Monitoring: Web applications often change their content dynamically; testing tools like Playwright help you ensure that changes to text or content are correctly reflected.
In 2026, as web apps become more dynamic, the need for precise and flexible text extraction methods is more critical than ever.
Understanding Locators in Playwright: How To Define Them for UI Testing
Before you can extract text from an element, you need to locate it in the DOM. Playwright offers several ways to do this, and the locator you choose affects how stable your extraction is when the page changes.
1. Built-in locators: getByRole, getByText
Playwright’s built-in locators target UI testing elements by role or visible text rather than raw DOM structure, which makes them more readable and far less likely to break when the page’s markup shifts.
- getByRole: finds an element by its role on the page, such as a button, link, or heading.
- getByText: finds an element by its visible text, which is especially useful for asserting that specific content is present.
2. CSS, XPath, and the :has-text() pseudo-class
For cases the built-in locators don’t cover, CSS selectors and XPath give you more control: CSS for targeting by attribute, class, or hierarchy and XPath for more complex relationships or text-based queries.
Playwright also adds its own :has-text() pseudo-class, which matches an element containing specific text anywhere inside it, even in a nested child, which is useful when the DOM structure around the text is likely to change.
What Are The Methods to Extract From an Element?
There are two methods which are the most common source of confusion in Playwright text extraction, because they can return different results for the exact same element.
1. innerText() returns only text that’s actually rendered on screen. If an element or its ancestor has display: none, that text is excluded. Use this when you’re validating what a real user would see.
/ <div id="status">Order <span style="display:none">delayed, </span>shipped</div>
await the page. locator('#status'). innerText(); // "Order shipped"Output –
2. textContent() returns every bit of text inside the element, hidden or not, and preserves things like extra whitespace. Use this when you need the raw DOM content, for example, scraping data that might be styled off-screen but is still present.
/ <div id="status">Order <span style="display:none">delayed, </span>shipped</div>
await page.locator('#status').textContent(); // "Order delayed, shipped"Output –
3. evaluate() for edge cases: When neither built-in method gives you what you need, say, text that’s generated by a script on interaction, or you need to combine DOM functions with extraction, `evaluate()` runs arbitrary JavaScript inside the page context.
const parentOnlyText = await page. locator('div.parent'). evaluate(el => el.firstChild.textContent);Output –
This is the escape, not the default. Reach for it only when innerText()/textContent() and locator chaining can’t get you there, since evaluate() code runs outside Playwright’s usual auto-waiting.
4. Reading form values: Text boxes inside inputs and textareas aren’t “content” in the same sense. It’s a value. Use inputValue() for these instead of the methods above:
const email = await page. locator('#email'). inputValue();Output –
Read More:Web Scraping with Playwright
What Are The Practical Code Examples in 2026 Playwright Setup
Understanding the methods is one thing, but applying them in real-world scenarios is another. Here are some practical examples of how you can set up your Playwright project and implement text extraction.
Setup Playwright Project (Node.js / TypeScript)
To get started, you need to set up Playwright in your project. For Node.js or TypeScript, you can initialize a new project and install Playwright via npm:
npm init -ynpm install playwrightAfter installation, you can create a test file to begin automating tasks and extracting text from elements.
Locating a Single Element and Reading Its Text
Once Playwright is set up, locating a single element and extracting its text is straightforward. For example:
const { chromium } = require(‘playwright’);(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(‘https://example.com’);
const text = await page.locator(‘h1’).innerText();
console.log(text);
await browser.close();
})();
This script navigates to a page and extracts the text from the ‘h1’ element.
Handling Lists/Arrays of Elements (e.g., Multiple
Items)
When dealing with multiple elements, such as a list of items, Playwright provides methods to handle arrays of elements. For example:
const listItems = await page.locator(‘ul li’).allTextContents();console.log(listItems);
This example extracts the text from all list items within an unordered list.
Extracting Only Parent-Text (Excluding Children)
To extract text from a parent element while excluding the children, you can use the .evaluate() method to access the DOM directly. Here’s how to get the text of a parent element while ignoring child elements:
const parentText = await page.locator(‘div.parent’).evaluate(el => el.firstChild.innerText);console.log(parentText);
What Are The Common Pitfalls And Best Practices For Playwright’s GetTextOfElement?
A handful of issues account for most text-extraction problems in Playwright. Here’s each one, paired with the fix.
- Hidden elements and whitespace. Text extraction can be thrown off by hidden elements or inconsistent styling. Confirm the element is actually visible before extracting, and trim whitespace before making assertions.
- Timing and auto-waits. Modern web apps often load content asynchronously, so the text you’re after may not exist yet at the moment you query for it. Playwright’s built-in auto-waiting handles most of this by waiting for the element to be ready before acting.
- Flaky, text-based locators. Locating elements purely by their text content is fragile; copy changes, and your locator breaks. Prefer stable locators like getByRole or getByTestId, which don’t depend on wording that products or marketing might change.
- Relying on visible text for test logic. Avoid using extracted text as the basis for a test’s branching logic. Text content changes far more often than the structure, so combining a locator with an attribute is more reliable than testing against copy directly.
- Performance on large element sets. When extracting text from many elements, use allTextContents() rather than looping and calling innerText() on each one individually; it’s built for bulk extraction and avoids the overhead of repeated round trips.
Beyond Testing: Other Uses for Text Extraction in Playwright
Text extraction isn’t only useful for test assertions; the same methods apply to two other common workflows:
- Data scraping: extracting product prices, reviews, or article content for storage or analysis, where textContent() is often the better fit since visibility doesn’t matter.
- Content monitoring: periodically extracting text to detect and alert on changes, useful for tracking pages where content updates without a clear signal, like pricing or availability pages.
Best Practices for Reliable Text Extraction in 2026
For robust and efficient text extraction, adhere to these best practices:
- Use Semantic Locators Where Available: When possible, use semantic locators like getByRole, getByLabelText, and getByText to ensure your tests are less brittle and more accessible. These locators are tied to the meaning of the element, not just its appearance.
- Avoid Depending on Visible Text Alone for Logic: Avoid using visible text alone to make assertions or decisions in your tests. Text content may change frequently, making it more reliable to combine locators and attributes to identify elements.
- Memory and Performance Considerations When Extracting Large Sets: When extracting text from a large number of elements, be mindful of performance. Playwright offers efficient methods like .allTextContents() to handle larger datasets without compromising speed or memory usage.
When and Why You Might Use Text Extraction (Beyond Testing)
Text extraction isn’t just for testing; it has broader applications in web scraping and monitoring.
- Data Extraction / Scraping vs UI Verification: Playwright’s ability to extract text can be used for scraping dynamic content, such as product prices, user reviews, or articles, and storing it for later use.
- Monitoring and Alerting Based on UI Text Changes: For sites with constantly changing content, text extraction can be used to monitor changes and trigger alerts when certain text appears or disappears, helping with real-time content validation.
Conclusion
Mastering text extraction in Playwright is a powerful skill that will help you automate, validate, and monitor web applications effectively. By understanding the different locators and methods for extracting text, you can write more reliable and efficient tests.
Also, consider integrating Playwright with cloud-based testing platforms like BrowserStack Automate to run tests at scale and across multiple devices.



