怎么给 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')
  }
}
  • 2020-03-09 22:11:39

    聊聊真实的 Android TV 开发技术栈

    智能电视越来越普及了,华为说四月发布智能电视跳票了,一加也说今后要布局智能电视,在智能电视方向,小米已经算是先驱了。但是还有不少开发把智能电视简单的理解成手机屏幕的放大,其实这两者并不一样。

  • 2020-03-11 09:43:20

    JavaScript shift() 方法

    shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。

  • 2020-03-11 09:45:19

    45个优秀的vue开源项目

    在过去一年里,前端开发发展迅速,前端工程师的薪资亦是水涨船高。2019 更是热度不减,而作为近年来尤为热门的前端框架,Vue.js 自是积累了大量关注。本文将为你介绍 2019 年最值得关注的 45 个 Vue.js 开源项目——Let's go!

  • 2020-03-11 18:26:52

    Mac设置ADB

    adb在 ~/Library/Android/sdk/platform-tools文件夹内

  • 2020-03-11 19:40:56

    java.util.zip.ZipException: zip file is empty

    三、总结 出现 java.util.zip.ZipException: zip file is empty错误,表示你本地使用的jar包或者aar包可能为空,你可以检查下文件大小,如果为空,可以替换本地的jar包或者aar包为正常的jar包或者aar包,或者如果官方有相关的资源的话直接使用官方的依赖资源即可。