简体   繁体   English

我将如何使用 puppeteer 解析请求的 cookies 并将它们保存到稍后调用的变量中?

[英]How would I parse requested cookies using puppeteer and save them to a variable to be called later?

im trying to parse specific valus from these cookies and save them to a variable to be used later but I cant seem to figure it out.我试图从这些 cookies 中解析特定值并将它们保存到一个变量中以供以后使用,但我似乎无法弄清楚。 Im using puppeteer to login and then request the cookies after logging in.我使用 puppeteer 登录,然后在登录后请求 cookies。

Im using puppeteers cookie request like this.我正在使用这样的 puppeteers cookie 请求。

const returnedCookies = await page.cookies()
console.log(returnedCookies); 

Which outputs this and a few other strings.它输出这个和其他一些字符串。 But I wanted to know how to get the value of that "mystate" and store it into a variable.但我想知道如何获取“mystate”的值并将其存储到变量中。

{
    name: 'mystate',
    value: '1614736342244',
    domain: '.target.com',
    path: '/',
    expires: -1,
    size: 20,
    httpOnly: false,
    secure: false,
    session: true,
    sameParty: false
  },

Any input at all would be appreciated.任何输入都将不胜感激。 Thank you:)谢谢:)

In your case returnedCookies is an array of objects.在您的情况下, returnedCookies是一个对象数组。 You can use find method for arrays to search through an array for one result:您可以使用arrays 的find方法在数组中搜索一个结果:

const returnedCookies = await page.cookies();
const cookieNeeded = returnedCookies.find((cookie) => cookie.name ==='mystate');

let value = null;

// If the desired cookie is found in the array, get its value
if(typeof cookieNeeded !== 'undefined') {
  value = cookieNeeded.value;
}

// If the needed cookie wasn't found `value` will be null
console.log(value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM