Puppeteer设置Cookies避免重复登录

2021-04-15 10:14:21

原理是先获得本机chrome的cookie,然后再设置给Puppeteer

参考地址 Using Cookies, Puppeteer & NodeJS To Mirror A Chrome Profile on macOS


Puppeteer!

Mirroring the state of one of your existing Chrome Profiles in Puppeteer can prove extremely useful for local projects and testing.

Unless you’re interested in simulating an entire login process, utilising pre-existing settings - in this case, cookies - can significantly reduce your time spent replicating a state that exists elsewhere on your machine.

The following process requires NodeJSNPM and Puppeteer. You’ll need to install all of those items in that order before going any further. Follow the instructions on their respective websites to get them installed on your system


The first issue is accessing the cookies. Cookies are encrypted for good reason: they contain sensitive information. On macOS, they’re ‘signed’ with a Chrome encryption key into an SQLite database which is managed by the OS keychain. In order to decrypt the signed cookies, your Node application must have access to the Chrome key inside the keychain. This requires authorisation by the logged in macOS user.

Node-Auth

Thankfully, there is an NPM module chrome-cookies-secure that is setup to handle this process. Copy and run the following code in your terminal (in the root of your project directory) to add the chrome-cookies-secure module to your project:

npm i --save chrome-cookies-secure

If you’re not prompted to authorise Node access to your keychain on the module install, don’t worry. You will be prompted when you run the basic NodeJS app described a little further down.

Next you’ll need to identify the path to the Chrome Profile you want to mirror (you may have multiple you’d like to choose from).

Open Chrome and make sure you’re browsing with the profile you want to retrieve the cookies for, and navigate to chrome://version. You’ll find the Profile of the current browser session under Profile Path.

Chrome-Profile

You can view all of your Chrome Profile directories at Users/yourName/Library/Application Support/Google/Chrome.

This is often written as ~/Library/Application Support/Google/Chrome where ~ refers to the user’s root directory (In Finder Macintosh HD > Users > userName = ~).


Now you have the basic information you need to retrieve your cookies within your Node app! Below is a simple code snippet to demonstrate the functionality. Let’s take a look at our https://www.google.com cookies.

In a file of your choosing inside your project folder (I’ve called mine server.js) paste in the following code:

const chrome = require('chrome-cookies-secure');

const url = 'https://www.google.com';

chrome.getCookies(url, 'puppeteer', function(err, cookies) {
    if (err) {
        console.log(err, 'error');
        return
    }
    // do stuff here...
    console.log(cookies, 'cookies');
}, 'yourProfile') // e.g. 'Profile 2'

The module does not yet fully support Promises or async/await, but we’re looking to add support. You can help us add it in at https://github.com/bertrandom/chrome-cookies-secureUpdate! March 2020 - there is a PR for a Promise wrapper awaiting approval - https://github.com/bertrandom/chrome-cookies-secure/pull/21

Get-Your-Cookies

Next, ensuring you’re in the project root directory in your terminal, run node yourfilename.js. You should see the cookies for the given profile and url you have chosen appear right there in the terminal, e.g:

Cookie-Output

In this example, we are looking at Google’s cookies. In the next section you will want to change this to a website where you are currently logged in


Now you can see your cookies in NodeJS, you can load them into Puppeteer!

Update your code to the following and run node yourfilename.js.

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'
}

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()
});

You’ll see Puppeteer open and navigate to your chosen site, and hopefully, providing there are no further security measures such as 2FA, you’ll see that you are logged in!

It’s worth noting there can be a thirty minute delay between new cookies in your Chrome Profile being reflected on your hard-drive (thus being accessible in your Node app). This is because Chrome persists cookies to storage once every thirty minutes. So if you have new cookies, give it 30 minutes and check it again.

You’ll also need to fully qualify URLs in order to retrieve all possible cookies for a given site i.e https://www.google.com not https://google.com.

But that’s it!

You should now be able to do what you want to do with Puppeteer, utilising a login state, preferences, or whatever else, from one of your Chrome Profiles!


  • 2018-04-19 16:32:47

    mysql binlog_do_db参数设置的坑

    在配置文件中想当然地配置成binlog_do_db=test,xx,jj,以为是三个库。结果无论什么操作都没有binlog产生

  • 2018-04-20 02:11:58

    Android中finish掉其它的Activity

    在Android开发时,一般情况下我们如果需要关掉当前Activity非常容易,只需要一行代码 this.finish;即可。 那么,如果是想要在当前Activity中关掉其它的Activity应该怎么实现呢? 比如更改了某个设定,程序需要重新运行并加载新的配置文件,就要用到restart或finish让程序重启。

  • 2018-04-20 09:12:07

    如何在 7 分钟内黑掉 40 家网站?

    去年夏天我开始学习信息安全与黑客技术。在过去的一年中,我通过参加各种战争游戏、夺旗以及渗透测试模拟,不断提高我的黑客技术,还学习了很多关于“如何让计算机偏离其预期行为”的新技术。

  • 2018-04-25 00:46:48

    Android开发笔记——SharedPreferences 存储实体类以及任意类型

    我们常常要用到保存数据,Android中常用的存储方式有SQLite,sharedPreferences 等,当然也有各自的应用场景,前者适用于保存较多数据的情形,后者责倾向于保存用户偏好设置比如某个checkbox的选择状态,用户登录的状态等等,都是以键值对的形式进行的文件读取,可以存储String,int,booean等一些基本数据类型等等。

  • 2018-04-25 11:48:44

    Java泛型详解

    泛型是Java中一个非常重要的知识点,在Java集合类框架中泛型被广泛应用。本文我们将从零开始来看一下Java泛型的设计,将会涉及到通配符处理,以及让人苦恼的类型擦除。

  • 2018-05-05 20:31:52

    StringUtils就这1张图,必备(二)

    StringUtils是工作中使用最频繁的一个工具类,提供了大量丰富的字符串操作方法,下面是所有方法的一个蓝图:

  • 2018-05-06 00:41:36

    设置EditText不自动聚焦

    如果界面中有EditText的时候,用户打开界面的话EditText就会自动聚焦。如果想取消这种一打开界面EditText就聚焦效果,可在EditText的上级父容器中加入如下代码: