怎么给 headless chrome添加cookies

2021-04-15 10:32:18

参考地址 How to manage log in session through headless chrome?

In puppeter you have access to the session cookies through page.cookies().

So once you log in, you could get every cookie and save it in a json file:

const fs = require(fs);const cookiesFilePath = 'cookies.json';// Save Session Cookiesconst cookiesObject = await page.cookies()// Write cookies to temp file to be used in other profile pagesfs.writeFile(cookiesFilePath, JSON.stringify(cookiesObject), function(err) { 
  if (err) {  console.log('The file could not be written.', err)
  }  console.log('Session has been successfully saved')
})

Then, on your next iteration right before using page.goto() you can call page.setCookie() to load the cookies from the file one by one:

const previousSession = fs.existsSync(cookiesFilePath)if (previousSession) {  // If file exist load the cookies
  const cookiesString = fs.readFileSync(cookiesFilePath);  const parsedCookies = JSON.parse(cookiesString);  if (parsedCookies.length !== 0) {    for (let cookie of parsedCookies) {      await page.setCookie(cookie)
    }    console.log('Session has been loaded in the browser')
  }
}
  • 2017-11-28 14:57:19

    vagrant up 失败解决办法

    直接使用VirtualBox开启一个vm也会失败,基本上可以确定是VirtualBox版本的问题 有遇到过安装了VirtualBox-5.0.22-108108-Win.exe的版本在win7下用不了,卸载重装VirtualBox-4.3.12-93733-Win.exe之后可用。

  • 2017-12-05 22:30:02

    php7.0升级php7.2

    看电脑上的教程要备份7.0配置文件以及扩展啥的,我感觉不如卸载干净重新安装

  • 2017-12-06 09:35:10

    分页优化的四种方式

    在大数据量的情况下,原本很简单的分页如果没有处理好,你会发现分页的请求会消耗你大量的数据库时间。如果你遇到了这个问题,文章给了你几个很好的解决的方案。当然,初学者若能看完这篇文章,那么它会指导你写出更具有扩展性的分页代码。