Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for text to appear when using Puppeteer

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});
like image 767
elena Avatar asked Oct 19 '17 08:10

elena


People also ask

How do you wait for an element in a puppeteer?

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.

How do you wait for the page to fully load in a puppeteer?

It is equivalent to waiting for the load event on the window: window. addEventListener("load", (event) => { console. log("page is fully loaded"); });

How do you get the text from the puppeteer button?

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.


3 Answers

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").inner‌​Text.length == 7');
like image 158
nilobarp Avatar answered Sep 23 '22 00:09

nilobarp


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.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.

like image 36
Thomas Dondorf Avatar answered Sep 25 '22 00:09

Thomas Dondorf


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

like image 41
Gilles Quenot Avatar answered Sep 25 '22 00:09

Gilles Quenot