Puppeteer
Browser Automation using Node.js and Puppeteer
Updated: 03 September 2023
Installing
To get started with Puppeteer you will need to install it to your package npm i puppeteer
this will install the required packages as well as a Google Chrome instance for Puppeteer
Basic Usage
In general, you will create a new browser
instance, and interact with that instance using the puppeteer api
. A basic example of using Puppeteer to take a screenshot can be seen below which will run a headless browser instance
Non-Headless Mode
Some of the settings that are available when creating a browser are the headless:false
and the slow-down speed slowMo
:
Screenshots
To navigate, type, and take some screenshots you can see the following:
Running JS Code in the Browser
It can sometimes be useful to execute arbitrary code in browser window that interacts with the DOM, for example replacing some text in the HTML. This can be done by using the .evaluate
function:
Alternatively, the .evaluate
function can also take data to share from the Node.js process to the browser process as a second argument, like so:
Connect to a Running Chrome Instance
To connect to a chrome instance, you can start chrome from your terminal and pass it the following argument:
The above will work on Windows, use the following for MacOS
You can also switch out port 9222
for any other port you want, thereafter use puppeteer.connect
instead of puppeteer.launch
like so:
Again, note that the port can be any port you like