I wonder if there's a similar way as in Selenium to wait for text to appear for a particular element. I've tried something like this, but it doesn't seem to wait:
await page.waitForSelector('.count', {visible: true});
waitForSelector() method. Wait for the selector to appear in page. If at the moment of calling the method the selector already exists, the method will return immediately. If the selector doesn't appear after the timeout milliseconds of waiting, the function will throw.
It is equivalent to waiting for the load event on the window: window. addEventListener("load", (event) => { console. log("page is fully loaded"); });
We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.
You can use waitForFunction
. See https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitforfunctionpagefunction-options-args
Including @elena's solution for completeness of the answer:
await page.waitForFunction('document.querySelector(".count").innerText.length == 7');
Apart from the method presented in the answer from nilobarp, there are two more ways to do this:
Using the pseudo selector :empty
it is possible to find elements that contain no child nodes or text. Combining this with the :not
selector, we can use page.waitForSelector
to query for a selector which is not empty:
await page.waitForSelector('.count:not(:empty)');
If you not only want to make sure that the element is not empty, but also want to check for the text it contains, you can use an XPath expression using page.waitForXPath
:
await page.waitForXPath("//*[@class='count' and contains(., 'Expected text')]");
This line will only resolve after there is an element on the page which has the attribute class="count"
and contains the text Expected text
.
The best solution you can do using waitForFunction()
(avoid weird function as string):
const selector = '.count';
await page.waitForFunction(
selector => document.querySelector(selector).value.length > 0,
{},
selector
);
Depends of the type of the text, replace value
by innerText
.
Check puppeteer API
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With