怎么给 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-04-01 23:23:27

    图像隐写之使用PHP隐藏图像中的文本

    隐写术是一门研究隐藏信息的科学艺术,通过隐写术,可以只让发送者和接收者知道隐藏的信息。 图像隐写术则是研究将数据隐藏在图像中,通过该技术可以防止无关用户发现这些隐藏的信息或数据。

  • 2019-04-08 16:01:57

    Window 设置pm2开机自启动服务

    下面用 pm2 来启动我们自己的服务程序 app.js, 然后告诉 pm2 开机后自动运行我 app.js 继续在管理员命令行下, cd 到 app.js 所在目录

  • 2019-04-10 17:25:21

    Joda-Time详解,最好用的java时间工具

    任何企业应用程序都需要处理时间问题。应用程序需要知道当前的时间点和下一个时间点,有时它们还必须计算这两个 时间点之间的路径。使用 JDK 完成这项任务将非常痛苦和繁琐。