我想要的是获取一个 cookie 并在我想打开一个已经登录的 puppeteer 实例时重新使用它。我试过了,但没有用:
获取 cookie 的函数:
async function writeCookies(page, cookiesPath) {
const client = await page.target().createCDPSession();
// This gets all cookies from all URLs, not just the current URL
const cookies = (await client.send("Network.getAllCookies"))["cookies"];
console.log(cookies)
console.log("Saving", cookies.length, "cookies");
// fs.writeFileSync(cookiesPath, JSON.stringify(cookies));
console.log(cookiesPath)
console.log(cookies)
// await fs.writeJSON(cookiesPath, cookies);
}
我是如何实现的:
const page = await browser.newPage();
time = new Date()
await page.goto("https://accounts.google.com/ServiceLogin/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1<mpl=default<mplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=AddSession")
await page.$eval('#identifierId', (el) => (el.value = "test@gmail.com"));
await page.click("#identifierNext > div > button > div.VfPpkd-RLmnJb");
await page.waitForSelector('#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input', { visible: true });
await page.$eval('#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input', (el) => (el.value = "Tester"));
await page.waitForSelector('#passwordNext > div > button > div.VfPpkd-RLmnJb', { visible: true });
await sleep(1000)
await page.click("#passwordNext > div > button > div.VfPpkd-RLmnJb");
writeCookies(page,"./WebHook.js")
我将如何发送 cookie:
await page.setExtraHTTPHeaders({cookies :`${cookies}`})
我也试过这种方式:
async function restoreCookies(page, cookiesPath) {
try {
// const cookies = await fs.readJSON(cookiesPath);
let buf = fs.readFileSync(cookiesPath);
let cookies = JSON.parse(buf);
console.log("Loading", cookies.length, "cookies into browser");
await page.setCookie(...cookies);
} catch (err) {
console.log("restore cookie error", err);
}
}
也许我检索了错误的 cookie。