怎么给 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-08 15:09:14

    IDEA从mapper.java跳转到mapper.xml

    在IDEA中写项目后台的时候,从controller到service到mapper到dao,都可以直接跳转,但是mapper.java到mapper.xml就需要自行寻找,为了开发方便,安装相应插件--mybais

  • 2019-09-08 21:44:15

    git pre-commit hook failed 解决办法

    今天在上传项目的时候在commit阶段遇到一个问题,无论是在Sourcetree上传还是用命令git commit -m 'xxx'都报了一下错误:

  • 2019-09-08 21:45:31

    git index.lock

    因是在你进行某些比较费时的git操作时自动生成,操作结束后自动删除,相当于一个锁定文件,目的在于防止对一个目录同时进行多个操作。 有时强制关闭进行中的git操作,这个文件没有被自动删除,之后你就无法进行其他操作,必须手动删除,进入.git文件中删除,打开显示隐藏文件。如果没有看见.git文件夹,可以直接用命令rm -f ./.git/index.lock。之后就可以正常使用。 ———————————————— 版权声明:本文为CSDN博主「李瑞豪」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_39520417/article/details/81941111

  • 2019-09-09 05:28:54

    IntelliJ IDEA 进阶教程: 语言注入

    我真的太久没发 IntelliJ 的教程了,最近 Sakura 同学找我帮他配 IntelliJ ,我秀了一下技术,假装自己是老司机。 然后发现 Language Injection 这个非常好用的功能我居然没写教程(很明显,一堆人不知道这个东西), 于是我又开始写教程了。 本文多图。

  • 2019-09-09 05:32:55

    SrpingBoot 热启动与热部署

    当我们已经启动了一个服务,然后修改代码之后,会自动重新部署。Spring项目通常有新内容修改后需要重新编译然后运行。通过配置Spring boot的热启动配置,可以实现自动编译重启项目,通常要比手动停止,启动项目快。