让Puppeteer使用本地个人资料的cookie

Pup*_*ser 8 google-chrome puppeteer

我想用Puppeteer使用我当地用户的个人资料.但是,它似乎不起作用.

我用这些args启动它.

const browser = await puppeteer.launch({
    executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
    userDataDir: '/Users/me/Library/Application Support/Google/Chrome',
});
Run Code Online (Sandbox Code Playgroud)

当无头时,它根本不使用用户的本地配置文件的cookie,即使我期望它.当它不是无头时,它甚至无法打开标签; Puppeteer崩溃了

(node:23303) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome!


TROUBLESHOOTING: https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md
Run Code Online (Sandbox Code Playgroud)

有没有办法使用我的本地用户的个人资料?我正在使用^1.7.0和Chrome 70.0.3521.2.

Ree*_*els 6

您可以使用NPM 包将 cookie 用于现有的 Chrome 配置文件之一,而不是在参数userDataDir中设置路径。此解决方案不需要安装 Chrome Canary。Puppeteer.launchchrome-cookies-secure

url通过您的 macOS 钥匙串授权,该包会从您的硬盘读取给定的 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()
});
Run Code Online (Sandbox Code Playgroud)

  • 您可以在 chrome://version/ 、`profilePath` 找到您的个人资料 (2认同)

use*_*079 5

我在 MacOS 上通过安装 chrome canary 解决了这个问题,将其中包含的默认文件夹复制~/Library/Application Support/Google/Chrome/Default~/Library/Application Support/Google/Chrome\ Canary/Default

我的工作代码如下所示:

async function run() {
  const browser = await puppeteer.launch({
    headless: false, 
    executablePath: '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary',
    userDataDir: '/Users/radium/Library/Application\ Support/Google/Chrome\ Canary/',
  });
}
Run Code Online (Sandbox Code Playgroud)

我之前一直使用文件路径到默认文件夹,并将其截断为以“Chrome Canary”文件夹结尾。这解决了一切。我还没有尝试过普通的镀铬。