怎么给 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-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包,或者如果官方有相关的资源的话直接使用官方的依赖资源即可。

  • 2020-03-11 21:22:36

    Vue的组件化之notification组件/Vue.extend()

    一、把组件的内部结构写好,写成一个vue文件notification.vue。 二、全局设置组件属性。//如果后面不需要直接引入组件的方式调用,可以不用全局注册 index.js中一般写的是需要全局设置的属性。

  • 2020-03-13 19:58:19

    推荐Android两种屏幕适配方案

    在Android开发中,由于Android碎片化严重,屏幕分辨率千奇百怪,而想要在各种分辨率的设备上显示基本一致的效果,适配成本越来越高。虽然Android官方提供了dp单位来适配,但其在各种奇怪分辨率下表现却不尽如人意,因此下面探索一种简单且低侵入的适配方式。本文将推荐两种屏幕适配方案,大家可以根据实际情况使用。