问题描述
我正在尝试:
- 访问初始化会话的页面
- 将会话存储在 JSON 对象中
- 访问同一页面,现在应该可以识别现有会话
我尝试的实现如下:
import puppeteer from 'puppeteer';
const createSession = async (browser, startUrl) => {
const page = await browser.newPage();
await page.goto(startUrl);
await page.waitForSelector('#submit');
const cookies = await page.cookies();
const url = await page.url();
return {
cookies,
url
};
};
const useSession = async (browser, session) => {
const page = await browser.newPage();
for (const cookie of session.cookies) {
await page.setCookie(cookie);
}
await page.goto(session.url);
};
const run = async () => {
const browser = await puppeteer.launch({
headless: false
});
const session = await createSession(browser, 'http://foo.com/');
// The session has been established
await useSession(browser, session);
await useSession(browser, session);
};
run();
createSession
用于捕获加载页面的 cookie.useSession
应使用现有 cookie 加载页面.
createSession
is used to capture the cookies of the loaded page.useSession
are expected to load the page using the existing cookies.
但是,这不起作用 - session.url
页面无法识别会话.似乎并非所有 cookie 都以这种方式被捕获.
However, this does not work – the session.url
page does not recognise the session. It appears that not all cookies are being captured this way.
推荐答案
page#cookies
似乎返回了一些带有 session=true,expires=0
配置的 cookie.setCookie
忽略这些值.
It appears that page#cookies
returns some cookies with the session=true,expires=0
configuration. setCookie
ignores these values.
我通过构建一个覆盖 expires
和 session
属性的新 cookie 数组来解决这个问题.
I worked around this by constructing a new cookies array overriding the expires
and session
properties.
const cookies = await page.cookies();
const sessionFreeCookies = cookies.map((cookie) => {
return {
...cookie,
expires: Date.now() / 1000 + 10 * 60,
session: false
};
});
在撰写此答案时,未记录 session
属性.请参阅以下问题 https://github.com/GoogleChrome/puppeteer/issues/980.
At the time writing this answer, session
property is not documented. Refer to the following issue https://github.com/GoogleChrome/puppeteer/issues/980.
这篇关于如何使用所有 cookie 重新创建页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!