【问题标题】:How to set cookies in a variable and use it again: PUPPETEER如何在变量中设置 cookie 并再次使用它: PUPPETEER
【发布时间】:2022-03-29 19:56:01
【问题描述】:

我正在尝试将所有浏览器 cookie 插入变量中,然后再使用它。

我的尝试:

    const puppeteer = require('puppeteer')
const fs = require('fs').promises;

(async () => {
  const browser = await puppeteer.launch({ 
    headless: false,
    executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
 const page = await browser.newPage();
 await page.goto('https://www.google.com/');

下面是我获取 cookie 的代码,它可以工作,但现在它会打印一条错误消息。

 const client = await page.target().createCDPSession();
 const all_browser_cookies = (await client.send('Network.getAllCookies')).cookies;
 const current_url_cookies = await page.cookies();
 var third_party_cookies = all_browser_cookies.filter(cookie => cookie.domain !== current_url_cookies[0].domain);
 

下面是第二个页面(将使用 cookie)

 (async () => {
    const browser2 = await puppeteer.launch({
    });
    const url = 'https://www.google.com/';
    const page2 = await browser2.newPage();

  try{
  await page2.setCookie(...third_party_cookies);
  await page2.goto(url);
  }catch(e){
      console.log(e);
  }
  await browser2.close()
  })();

})();

直到昨天它工作,但今天它出现此消息错误:

Error: Protocol error (Network.setCookies): Invalid parameters Failed to deserialize params.cookies.expires - BINDINGS: double value expected at position 662891

有人知道是什么吗?

【问题讨论】:

    标签: javascript node.js puppeteer


    【解决方案1】:

    好的,解决方法在这里:https://github.com/puppeteer/puppeteer/issues/7029

    您正在保存一组 cookie,而 page.setCookie 仅适用于一个 cookie。你必须像这样迭代你的数组:

    for (let i = 0; i < third_party_cookies.length; i++) {
        await page2.setCookie(third_party_cookies[i]);
    }
    

    【讨论】:

      【解决方案2】:

      @julio-codesal 的建议是可以的,但是根据 puppeteer 文档,可以将 page.setCookie 与数组一起使用,只要您对其进行解构即可,例如:

      await page.setCookie(...arr)
      

      来源:https://devdocs.io/puppeteer/index#pagesetcookiecookies

      不完全确定它是什么,但 OP 的错误是另一回事。

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 2018-12-11
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2020-06-07
      相关资源
      最近更新 更多