I am testing a web application using Playwright on a Windows environment with Node.js version 14. I need to extract dynamically changing text from a web page using the innerText method but am facing issues.
I have tried using:
page.innerText('selector')
However, it sometimes returns an empty string or throws an error saying the element is not visible. I expected it to retrieve the actual text content from visible elements on the page.
How can I properly useinnerText in Playwright when dealing with dynamic content or visibility delays?
This issue is usually caused by timing. Playwright executes quickly, and if the element hasn’t fully loaded or become visible, innerText() may return an empty string or throw an error.
A reliable approach is to wait for the element first:
await page.waitForSelector('selector');
const text = await page.innerText('selector');
This ensures the element exists in the DOM before retrieving its text.
If your content loads via API calls or animations, you may need to wait for those operations to complete. In many cases, simply adding waitForSelector() resolves the issue.
Sometimes the problem is not just DOM presence but visibility. innerText() works only on visible elements. If the element is hidden (even temporarily), it may fail.
You can explicitly wait for visibility:
await page.waitForSelector('selector', { state: 'visible' });
const text = await page.innerText('selector');
Alternatively, you can wait for a visibility condition:
await page.waitForFunction(() =>
document.querySelector('selector')?.offsetParent !== null
);
const text = await page.innerText('selector');
This checks that the element is actually visible before extracting text.
Also verify:
The selector is correct and not matching multiple elements unexpectedly.
The element is not hidden by CSS (display: none, visibility: hidden).
No late-running JavaScript is replacing the content.