我想在 Puppeteer 中使用本地用户的个人资料。不过好像没啥作用。
我用这些参数启动它。
const browser = await puppeteer.launch({
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
userDataDir: '/Users/me/Library/Application Support/Google/Chrome',
});
当 headless 时,它根本不使用用户本地配置文件的 cookie,尽管我希望如此。当它不是 headless 时,它甚至无法打开选项卡; Puppeteer 崩溃了
(node:23303) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome!
TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md
有办法使用我的本地用户的个人资料吗?我使用的是 ^1.7.0
和 Chrome 70.0.3521.2
。
最佳答案
您可以使用chrome-cookies-secure
,而不是在Puppeteer.launch
参数中设置userDataDir
路径。 NPM 包将 cookie 用于您现有的 Chrome 配置文件之一。此解决方案不需要安装 Chrome Canary。
通过您的 macOS 钥匙串(keychain)授权,该软件包会从您的硬盘读取给定 url
的 cookie,并让它们在 NodeJS 中进行访问。然后,您可以使用 page.setCookie(...)
方法将它们加载到 Puppeteer 中。
这是一个例子:
const chrome = require('chrome-cookies-secure');
const puppeteer = require('puppeteer');
const url = 'https://www.yourUrl.com';
const getCookies = (callback) => {
chrome.getCookies(url, 'puppeteer', function(err, cookies) {
if (err) {
console.log(err, 'error');
return
}
console.log(cookies, 'cookies');
callback(cookies);
}, 'yourProfile') // e.g. 'Profile 2'
}
// find profiles at ~/Library/Application Support/Google/Chrome
getCookies(async (cookies) => {
const browser = await puppeteer.launch({
headless: false
});
const page = await browser.newPage();
await page.setCookie(...cookies);
await page.goto(url);
await page.waitFor(1000);
browser.close()
});
关于google-chrome - 让 Puppeteer 使用本地配置文件的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51865092/