When working with Puppeteer, you can save and reuse session cookies in order to maintain the state of a session between different browser instances or runs of your script. Here is a step-by-step guide on how to achieve this:
page.cookies()
method which returns an array of cookies currently set for the page. You can then save this array to a file using fs.writeFileSync()
.const fs = require('fs');
const cookies = await page.cookies();
fs.writeFileSync('cookies.json', JSON.stringify(cookies));
page.setCookie()
method. This will allow you to reuse the session cookies from a previous session.const cookies = JSON.parse(fs.readFileSync('cookies.json', 'utf8'));
for (let cookie of cookies) {
await page.setCookie(cookie);
}
By following these steps, you can save and reuse session cookies with Puppeteer, allowing you to maintain the state of a session between different browser instances or runs of your script.