如何通过无头 chrome 管理登录会话? [英] How to manage log in session through headless chrome?

查看:34
本文介绍了如何通过无头 chrome 管理登录会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个刮板:

  1. 打开无头浏览器,
  2. 转到网址
  3. 登录(有steam oauth),
  4. 填充一些输入,
  5. 然后点击 2 个按钮.

我的问题是每次无头浏览器的新实例都会清除我的登录会话,然后我需要一次又一次地登录...

My problem is that every new instance of headless browser clears my login session, and then I need to login again and again...

如何通过实例保存它?(使用带有无头 chrome 的 puppeteer)

How to save it through instances? (using puppeteer with headless chrome)

或者 如何打开已经登录的 Chrome 无头实例?(如果我已经登录到我的主 chrome 窗口)

Or how can I open already logged in chrome headless instance? (if I have already logged in in my main chrome window)

推荐答案

在 puppeter 中,您可以通过 page.cookies() 访问会话 cookie.

In puppeter you have access to the session cookies through page.cookies().

因此,一旦您登录,您就可以获取每个 cookie 并将其保存在一个 json 文件中:

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 Cookies
const cookiesObject = await page.cookies()
// Write cookies to temp file to be used in other profile pages
fs.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')
})

然后,在使用 page.goto() 之前的下一次迭代中,您可以调用 page.setCookie() 从文件中一个一个地加载 cookie:

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')
  }
}

查看文档:

这篇关于如何通过无头 chrome 管理登录会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆