Puppeteer 的 page.cookies() 未检索 Chrome 开发工具中显示的所有 cookie

Puppeteer's page.cookies() not retrieving all cookies shown in the Chrome dev tools

使用 puppeteer,我正在尝试从 Node.js.

检索特定网站(即 https://google.com)的所有 cookie

我的代码是:

// Launch browser and open a new page
const browser = await puppeteer.launch({ headless: true, args: ['--disable-dev-shm-usage'] });
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle2' });
var cookies = await page.cookies();
console.log(cookies);
await browser.close();

它只检索 2 个 cookie,名为 1P_JARNID。但是,当我打开 Chrome 开发工具时,它显示的内容更多。

我尝试直接使用 Chrome 开发工具而不是 puppeteer,但我得到了相同的结果。

我应该调用另一个函数吗?我做得对吗?

谢谢@try-catch-finally。我解决了它,这是一个简单的菜鸟错误。 我正在将我自己的 Google Chrome 实例中的 cookie 与 Puppeteer 实例进行比较。但是,在我的例子中,我登录了我的 Google 帐户,而 Puppeteer(显然)没有登录。 Google 在您未登录时使用 2 个 cookie,在您登录时使用 12 个。

page.cookies() 调用仅获取浏览器内 JavaScript 应用程序可用的 cookie,而不是您在 Chrome 中看到的标记为 httpOnly 的 cookie开发工具。解决方案是通过 Devtools 协议请求所有可用的 cookie,然后过滤您感兴趣的站点。

var data = await page._client.send('Network.getAllCookies');

如果您使用 Playwright 代替 Puppeteer,则可以轻松访问 httponly cookie:

const { chromium } = require('playwright')
(async () => {
    const browser = await chromium.launch()
    const context = await browser.newContext()
    const page = await context.newPage()
    await page.goto('https://google.com', { waitUntil: 'networkidle' })
    let allCookies = await context.cookies()
    console.log (allCookies)
})();

returns:

[
  {
    sameSite: 'None',
    name: '1P_JAR',
    value: '2021-01-27-19',
    domain: '.google.com',
    path: '/',
    expires: 1614369040.389115,
    httpOnly: false,
    secure: true
  },
  {
    sameSite: 'None',
    name: 'NID',
    value: '208=VXtmbaUL...',
    domain: '.google.com',
    path: '/',
    expires: 1627588239.572781,
    httpOnly: true,
    secure: false
  }
]

您可以利用 Chrome DevTools Protocol -> getAllCookies 获取所有浏览器 cookie,而不考虑任何标志。

const client = await page.target().createCDPSession();
const cookies = (await client.send('Network.getAllCookies')).cookies;

这也适用于 typescript 和 tslint,因为

const cookies = await page._client.send('Network.getAllCookies');

将引发错误 TS2341: Property '_client' is private and only accessible within class 'Page'.