Node.js 如何在Puppeter中使用会话cookie进行身份验证

Node.js 如何在Puppeter中使用会话cookie进行身份验证,node.js,puppeteer,Node.js,Puppeteer,我想存储会话cookie并使用Puppeter验证我的帐户。 现在我直接使用我的用户名和密码进行身份验证 下面是一个如何使用Puppeter登录web应用程序的示例。您需要安装(一个npm模块) 在Puppeter中保存会话Cookies const cookiesObject = await page.cookies() // Write cookies to temp file to be used in other profile pages jsonfile.writeFile(cook

我想存储会话cookie并使用Puppeter验证我的帐户。

现在我直接使用我的用户名和密码进行身份验证


下面是一个如何使用Puppeter登录web应用程序的示例。您需要安装(一个npm模块)

在Puppeter中保存会话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
  }
}
这些实例用于讨论原始Chrome Devtools协议:

  • 可以使用
    会话.send
    方法调用协议方法
  • 协议事件可以使用
    会话.on
    方法订阅
以下是这些网站的官方链接:


存储Cookie、txt或JSONit的临时文件应该是什么文件格式。txt文件是否有其他不带Apify的解决方案参见此,它似乎回答了同样的问题,不带Apify:
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')
})
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
  }
}