When using Puppeteer there are times when you may need to wait for text to display on a page - perhaps to ensure that the page has fully loaded or before executing another step in your automation pipeline.
Here is a (pseudo-code) solution to this problem:
The full details are outlined below.
Let’s dive in and Geppetto it up!
Step by Step Guide
For this example we will load up espn.com (which is a relatively large site) and check for the text “NBA”. You can use this example to load up any site and wait for any text. However, please be aware of Puppeteer’s default timeout of 30 seconds when doing so and extend it accordingly if your situation requires.
Create a browser instance
Create a new page
Navigate to the desired URL
Check to see if text exists on the page
Do something now that the page has loaded (e.g. take a screenshot)
The full script
Run the script (assumes the code is saved to “
Bonus - making the script more reusable
This version stores our
text values at the top of the file for easier modification. Notice how we now pass in a function instead of a string to the
waitForFunction. We also send over arguments from node.js as the third parameter. I leave it up to the reader to pass these in via the command line or via a separate module. Additionally, I added a little error handling by wrapping our
waitForFunction in a
We have created a solution that will wait for text on a page to appear before proceeding to the next step in execution. This script is helpful if you have any server side scripts (e.g. PHP) that may render text on the page by modifying the DOM without changing the URL. Good luck with your puppeteering and check out the additional resources below. Happy coding!