Puppeteer设置Cookie报错:提示缺少name/value但实际已存在
问题
使用Puppeteer设置Cookie时遇到类型错误,报错显示参数为Cookie数组无法赋值给CookieParam类型,提示缺少name和value属性,但Cookie变量中明明包含这两个属性。
Cookie变量代码:
const cookies = [{ domain: ".apollo.io", expirationDate: 1703861523, hostOnly: false, httpOnly: false, name: "__hssc", path: "/", sameSite: "lax", secure: false, session: false, storeId: "0", value: "21978340.1.170385", id: 1, }, ]
调用setCookie的代码:
await page.setCookie(cookies);
报错信息:
error TS2345: Argument of type '{ domain: string; expirationDate: number; hostOnly: boolean; httpOnly: boolean; name: string; path: string; sameSite: string; secure: boolean; session: boolean; storeId: string; value: string; id: number; }[]' is not assignable to parameter of type 'CookieParam'. Type '{ domain: string; expirationDate: number; hostOnly: boolean; httpOnly: boolean; name: string; path: string; sameSite: string; secure: boolean; session: boolean; storeId: string; value: string; id: number; }[]' is missing the following properties from type 'CookieParam': name, value
已尝试逐一检查Cookie属性、修改类型、搜索CookieParam定义、给键加引号等方法,仍无法解决,求问题原因及解决办法。
完整代码:
import puppeteer from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; const defaultPuppeteerOptions = {headless:false}; const ApolloUrl = 'https://apollo.io'; const cookies = [{ domain: ".apollo.io", expirationDate: 1703861523, hostOnly: false, httpOnly: false, name: "__hssc", path: "/", sameSite: "lax", secure: false, session: false, storeId: "0", value: "21978340.1.1703859723", id: 1, }, ] export default async function Start() { const browser = await puppeteer.launch(defaultPuppeteerOptions); const page = await browser.newPage(); await page.goto(ApolloUrl); await page.setCookie(cookies); }
解决方法
问题核心是page.setCookie()的调用方式错误:
- Puppeteer的
page.setCookie()方法接受单个CookieParam对象,或多个CookieParam对象作为独立参数,不支持直接传入Cookie数组。 - 你把整个数组作为单个参数传入,TypeScript会判定该数组不符合
CookieParam的结构(数组本身没有name、value属性),因此抛出错误。
修复步骤
- 修改setCookie调用方式:使用扩展运算符将数组展开为独立参数
await page.setCookie(...cookies);
- 清理冗余属性:你的Cookie对象包含
id和storeId,这两个不属于Puppeteer的CookieParam规范字段,建议移除避免潜在类型问题:
const cookies = [{ domain: ".apollo.io", expirationDate: 1703861523, hostOnly: false, httpOnly: false, name: "__hssc", path: "/", sameSite: "lax", secure: false, session: false, value: "21978340.1.1703859723", }, ]
- 调整执行顺序:建议先设置Cookie再访问页面,确保页面加载时Cookie已生效:
export default async function Start() { const browser = await puppeteer.launch(defaultPuppeteerOptions); const page = await browser.newPage(); await page.setCookie(...cookies); await page.goto(ApolloUrl); }
内容的提问来源于stack exchange,提问作者Pedro Santos
相关产品推荐
相关产品推荐

