Wait for text to appear when using puppeteer

穿精又带淫゛_ 提交于 2019-11-29 13:27:26

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');

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!