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});
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:
page.waitForSelector
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)');
XPath expression
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.waitForX
:
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
来源:https://stackoverflow.com/questions/46825300/wait-for-text-to-appear-when-using-puppeteer