Cookie
Puppeteer 提供了方法来提前获取、设置和删除 cookie,通过直接操作浏览器存储来实现。 如果您需要在测试中存储和恢复特定的 cookie,这将非常有用。
获取 Cookie
以下示例演示了如何获取浏览器默认BrowserContext中可用的 cookie。
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// In this example, we set a cookie using script evaluation.
// Cookies can be set by the page/server in various ways.
await page.evaluate(() => {
document.cookie = 'myCookie = MyCookieValue';
});
console.log(await browser.cookies()); // print available cookies.
设置 Cookie
Puppeteer 还可以直接将 cookie 写入浏览器存储
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
// Sets two cookies for the localhost domain.
await browser.setCookie(
{
name: 'cookie1',
value: '1',
domain: 'localhost',
path: '/',
sameParty: false,
expires: -1,
httpOnly: false,
secure: false,
sourceScheme: 'NonSecure',
},
{
name: 'cookie2',
value: '2',
domain: 'localhost',
path: '/',
sameParty: false,
expires: -1,
httpOnly: false,
secure: false,
sourceScheme: 'NonSecure',
},
);
console.log(await browser.cookies()); // print available cookies.
删除 Cookie
Browser.deleteCookie()方法允许从存储中删除 cookie。
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
// Deletes two cookies for the localhost domain.
await browser.deleteCookie(
{
name: 'cookie1',
value: '1',
domain: 'localhost',
path: '/',
sameParty: false,
expires: -1,
httpOnly: false,
secure: false,
sourceScheme: 'NonSecure',
},
{
name: 'cookie2',
value: '2',
domain: 'localhost',
path: '/',
sameParty: false,
expires: -1,
httpOnly: false,
secure: false,
sourceScheme: 'NonSecure',
},
);
console.log(await browser.cookies()); // print available cookies.
除了在默认浏览器上下文中操作的 Browser
方法外,相同的方法也可在 BrowserContext
类上使用。