How to save cookies and load it in another puppeteer session?

后端 未结 1 1148
忘掉有多难
忘掉有多难 2020-12-17 14:22

I had to request the same webpage twice to get the cookies in the 1st request and use it in the 2nd request in the following example.

Could anybody show me the code

1条回答
  •  失恋的感觉
    2020-12-17 14:45

    To save the cookies, you can use the function page.cookies. To reuse the cookies, you can use the page.setCookies function.

    Save cookies to disk

    const fs = require('fs').promises;
    
    // ... puppeteer code
    const cookies = await page.cookies();
    await fs.writeFile('./cookies.json', JSON.stringify(cookies, null, 2));
    

    This will read the cookies for the current URL and save them to disk via JSON.stringify and fs.writeFile.

    Reuse cookies

    const fs = require('fs').promises;
    
    // ... puppeteer code
    const cookiesString = await fs.readFile('./cookies.json');
    const cookies = JSON.parse(cookiesString);
    await page.setCookie(...cookies);
    

    To reuse the cookies, read the files from the disk via fs.readFile. Then parse the file content via JSON.parse. After that you have to call the page.setCookie function. As the function expects the cookies as arguments (and not as one array argument with cookies), we rely on the spread operator, which allows to call the setCookie function with the given cookies array as individual arguments.

    0 讨论(0)
提交回复
热议问题