如何通过无头chrome管理登录会话? [英] how to manage log in session through headless chrome?
问题描述
我需要制作刮刀:
打开无头浏览器,转到 url ,登录(有蒸汽oauth),填写一些输入,点击2个按钮
open headless browser, go to url, log in (there is steam oauth), fill some inputs, click 2 buttons
问题是无头浏览器的每个新实例都清除我的登录会话,然后我需要一次又一次登录...如何通过实例保存?
例如使用带无头镀铬的puppeteer
problem is every new instance of headless browser clears my login session, and then i need to login again and again...how to save it through instances? for example using puppeteer with headless chrome
或者我如何打开已登录的chrome无头实例?如果我已经在我的主要Chrome窗口中登录
or how can i open already logged in chrome headless instance? if i already log in in my main chrome window
推荐答案
在puppeter中,您可以通过 page.cookies()
。
In puppeter you have access to the session cookies through page.cookies()
.
因此,一旦您登录,您就可以使用 jsonfile :
So once you log in, you could get every cookie and save it in a json file using jsonfile:
// 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:
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 = 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
- https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagecookiesurls
- https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagesetcookiecookies
这篇关于如何通过无头chrome管理登录会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!