page cookies in puppeteer not work for keep login

Viewed 5977

i want make a web scraper on https://web.whatsapp.com for sending message to my customers i want save my login for next use that no need to re-scan the qr-code i know that i have to save cookie and set in for next use after scan qr and login to my account i see cookie in google chrome dev tools,application tab and cookie section but page.cookie is empty and return [] I tried to store cookies in a file using a sample code.after running code mycookie.json created and [] is in.

how can do it?

const puppeteer = require('puppeteer');
const jsonfile = require('jsonfile');
(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        args: ['--start-maximized']
    });
    const page = await browser.newPage();
    await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36');
    await page.setViewport({ width: 1280, height: 800 });
    await page.goto('https://web.whatsapp.com/', {waitUntil: 'networkidle0'});
    await page.setViewport({
        width: 1440,
        height: 900
    });
    await page.waitFor(10000);//wait for scan qr
    console.log(await page.cookies());

    // Save Session Cookies
    var cookiesFilePath = 'mycookie.json';
    const cookiesObject = await page.cookies();
    // Write cookies to temp file to be used in other profile pages
    jsonfile.writeFile(cookiesFilePath, cookiesObject, { spaces: 2 },
     function(err) { 
      if (err) {
      console.log('The file could not be written.', err)
      }
      console.log('Session has been successfully saved')
    })
})();
1 Answers

You should use userDataDir If you use that you won't lose your browser data. Even if you get cookie data that won't help you because web WhatsApp uses local-storage as well.

Example

const browser = await puppeteer.launch({
     headless: false,
     args: ['--start-maximized'],
     userDataDir: '<PATH>' // './cache' for example   
});

The directory defined in the PATH variable must exist!

References https://github.com/GoogleChrome/puppeteer/blob/v1.20.0/docs/api.md#puppeteerdefaultargsoptions
https://docs.browserless.io/blog/2019/05/03/improving-puppeteer-performance.html#launch-with-a-user-data-dir
https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md

Related