怎么给 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')
  }
}
  • 2019-09-11 15:28:07

    Node 性能优化

    硬盘的 IO 开销是非常昂贵的,硬盘 IO 花费的 CPU 时钟周期是内存的 41000000/250 = 164000 倍。 所有在一般应用中,优化要首先考虑数磁盘 IO , 通常也就是数据层的优化,说到数据库优化,很多人第一时间会想到加索引,但是什么加了索引查询会变快呢?索引要怎么加才合适呢?

  • 2019-09-11 16:49:56

    flex布局详解,Flex 布局语法教程

    布局的传统解决方案,基于盒状模型,依赖 display属性 + position属性 + float属性。它对于那些特殊布局非常不方便,比如,垂直居中就不容易实现

  • 2019-09-12 16:32:19

    JSLint,JSHint,ESLint的区别

    主流的JS Lint工具及介绍 JavaScript已经发展蛮长时间了,对应的Lint工具也是层出不穷,下面介绍一下比较主流的几个Lint工具(其实是我用过的几个XD)

  • 2019-09-16 22:56:52

    java.lang.NoSuchMethodError:SpringJAR包版本冲突错误解决方法

    查询了相关资料,大部分都说引起的原因是JAR包错误或JAR包冲突,查看了配置文件,并没有发现错误之处,因为用的是maven工程,这让我想到了maven的JAR引用的传递性,应该是引用的JAR包中传递引用了相同的包,没有排除。通过mvn dependency:tree 命令查看当前工程引用的依赖JAR树