怎么给 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-02-26 20:16:49

    一条简单的命令就可以将 stylus 语法转换为 scss 语法

    因为早期有个项目用到了 stylus,stylus 开发起来很爽,但 stylus 基于缩进的代码在修改的时候不是很方便,加上所在团队开发使用的都是 SCSS ,为了便于维护和统一,准备将项目中的 stylus 替换成 SCSS。手动转换 stylus 浪费时间,且出错率大,当时在想也许别人也有这样的需求呢,所以就做了这样一个项目。请各位大佬动动你们发财的小手,给我点个 star,不胜感激。^_^

  • 2020-02-27 09:01:32

    npm yarn 命令对比

    Yarn 是 Facebook, Google, Exponent 和 Tilde 开发的一款新的 JavaScript 包管理工具。就像我们可以从官方文档了解那样,它的目的是解决这些团队使用 npm 面临的少数问题.

  • 2020-02-29 20:47:34

    Nuxt 特有函数和变量

    asyncData方法使得你能够在渲染组件之前异步获取数据。该方法在服务端中执行的,所以,请求数据时,不存在跨域问题。返回的数据将与 data() 返回的数据进行合并。由于asyncData方法是在组件 初始化 前被调用的,所以在方法内是没有办法通过 this 来引用组件的实例对象。

  • 2020-03-01 19:00:46

    触发onclick事件元素的获取

    自动生成元素的onclick事件 event.target返回触发事件的元素 event.currentTarget返回绑定事件的元素

  • 2020-03-03 09:46:42

    JS实现HTML标签转义及反转义

    简单说一下业务场景,前台用户通过input输入内容,在离开焦点时,将内容在div中显示。 这时遇到一个问题,如果用户输入了html标签,则在div显示中,标签被解析。 由于是纯前端操作,不涉及后端,因此需要通过js对输入内容进行转义。