0

When I try to log in to a website using Puppeteer, I am able to do so. My problem is when I try to reset the cookie to not repeat the login process the below is my login logic.

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    defaultViewport: null, // set defaultViewport to null
  });
  const page = await browser.newPage();
  const link = 'https://www.reuters.com/account/sign-in/?redirect=https%3A%2F%2Fwww.reuters.com%2F'

  await page.goto(link, {
    waitUntil: "networkidle2",
  });

  // const elementHandle = await page.$('a[href*="/signin/"].button__link__uTGln.button__secondary__18moI.button__round__1nYLA.text-button__container__3q3zX.site-header__button__RTOI5');
  // await elementHandle.click();
  await page.waitForSelector('input[name="email"]');
  await page.waitForSelector('input[name="password"]');

  await page.type('input[name="email"]', "email@email.com");
  await page.type('input[name="password"]', "myComplicatedPassword");

  await sleep(1000);
  await page.click('.sign-in-form__sign-in-btn__2jvFh')

  await sleep(10000);

  //save cookies
  const cookies = await page.cookies();
  await fs.writeFile('./cookies.json', JSON.stringify(cookies, null, 2));

  await browser.close();
})();

And this is the logic for setting the cookie:

(async () => {
const browser = await puppeteer.launch({
    headless: false,
    executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    defaultViewport: null, // set defaultViewport to null
    });
    const page = await browser.newPage();

  //load cookies
  const cookiesString = await (await fs.readFile("./cookies.json"));
  const cookies = JSON.parse(cookiesString);

  await page.setCookie(...cookies);
    console.log(await page.cookies('https://www.reuters.com/'))
  await page.goto("https://www.reuters.com/");

//   await browser.close();
})();

Where am I going wrong?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • Do you get any errors? Are the contents of `cookiesString` what you expect them to be? Why are there two `await`s here (cosmetic, but still odd)? Generally speaking, [prefer `waitForSelector` or some other predicate rather than sleeping](https://stackoverflow.com/a/73676564/6243352) once you finish debugging this. – ggorlen Feb 23 '23 at 03:10
  • @ggorlen i've tried several variants for waiting, and it seemed to wait for the home redirect, and regarding the await this is a typo my bad the cookie contents are exactly what i expect them to be... is it possible that localstorage is not being set, since when i open a regular browser and log to reuters.com then delete the localstorage this logs me out, could the issue be localstorage? – Hicham Al Walli Feb 23 '23 at 10:08

0 Answers0