怎么给 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-06-10 11:54:52

    html.div禁用点击事件

    今天做项目中偶然误把元素加上了pointer-events属性,结果导致后来在js中给该元素加点击事件不能用,检查了半天才发现是这个属性的问题。之前没有好好研究,于是决定仔细研究一下。

  • 2019-06-12 22:34:16

    PHP身份证号打星号

    一个很简单的问题,想把身份证的号生日的4位隐藏,一开始查函数居然没有看到,然后用了好几个函数处理,觉得太麻烦就上网搜,后来发现有一个函数就能直接处理,我居然没看到~~初学者~~

  • 2019-06-13 10:09:51

    java(Android)跨Module调用对应类方法需求解决方案

    在开发组件化项目中,遇到一个这样的问题,两个不同的Module相互之间没有任何直接依赖关系,现在需求是需要在Module_A中调用Module_B中的某个类的方法,以下为解决此问题的方法;

  • 2019-06-13 11:31:32

    Android Studio接入ARouter以及简单使用

    你可能会说如果我的A module依赖了 B module,那么只要在B里面配置是不是就可以了?绝对不行!无论module之间关系如何,必须要同样配置!包括主项目和library项目!

  • 2019-06-13 11:34:24

    Android组件化方案

    1为什么要项目组件化 2如何组件化 3组件化实施流程