javascript – 如何通过无头chrome管理登录会话?

我需要刮刀:

打开无头浏览器,转到url,登录(有蒸汽oauth),填写一些输入,点击2按钮

问题是无头浏览器的每个新实例都清除我的登录会话,然后我需要一次又一次地登录…如何通过实例保存它?
例如使用带无头镀铬的木偶操纵者

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

解决方法:

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

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

// Save Session Cookies
const cookiesObject = await page.cookies()
// Write cookies to temp file to be used in other profile pages
jsonfile.writeFile(cookiesFilePath, cookiesObject, { spaces: 2 },
 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:

const previousSession = fileExistSync(cookiesFilePath)
if (previousSession) {
  // If file exist load the cookies
  const cookiesArr = require(`.${cookiesFilePath}`)
  if (cookiesArr.length !== 0) {
    for (let cookie of cookiesArr) {
      await page.setCookie(cookie)
    }
    console.log('Session has been loaded in the browser')
    return true
  }
}

查看文档:

> https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagecookiesurls
> https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagesetcookiecookies

上一篇:javascript – 如何在任何Web浏览器中运行Puppeteer代码?


下一篇:javascript – 等待使用puppeteer时出现文本