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!


  • 2019-03-26 19:25:01

    Android studio 打包后安装闪退 Fatal Signal 6(SIGABRT)...

    项目上线前打包安装后闪退,查了很多原因,比如混淆文件的内容,第三方库不加入混淆等等,均未成功,后来关闭混淆打包后运行成功,原因可能是依赖工程中的库文件不能被混淆,关闭本工程混淆开关后,依赖工程的混淆开关也要关闭,关闭混淆后如果怕被反编译,可使用百度开发平台的app加固,加固的同时还能使用多渠道打包工具。

  • 2019-03-26 19:29:05

    Android NDK开发Crash错误定位

     在Android开发中,程序Crash分三种情况:未捕获的异常、ANR(Application Not Responding)和闪退(NDK引发错误)。其中未捕获的异常根据logcat打印的堆栈信息很容易定位错误。ANR错误也好查,Android规定,应用与用户进行交互时,如果5秒内没有响应用户的操作,则会引发ANR错误,并弹出一个系统提示框,让用户选择继续等待或立即关闭程序。并会在/data/anr目录下生成一个traces.txt文件,记录系统产生anr异常的堆栈和线程信息。如果是闪退,这问题比较难查, --------------------- 作者:xyang0917 来源:CSDN 原文:https://blog.csdn.net/xyang81/article/details/42319789 版权声明:本文为博主原创文章,转载请附上博文链接!

  • 2019-04-01 22:46:39

    电子签章的实施方案

    WORD/EXCEL签章模块,该部分实现与WORD/EXCEL的无缝结合,并提供给用户简单直观的菜单和工具条来实现文档签章验证等各种操作,其中,KHSC-64智能密码钥匙是签章模块中用户证书和图章的载体

  • 2019-04-01 22:48:25

    如何用 Java 对 PDF 文件进行电子签章

    印章是我国特有的历史文化产物,古代主要用作身份凭证和行驶职权的工具。它的起源是由于社会生活的实际需要。早在商周时代,印章就已经产生。如今的印章已成为一种独特的,融实用性和艺术性为一体的艺术瑰宝。传统的印章容易被坏人、小人私刻;从而新闻鲜有报道某某私刻公章,侵吞国家财产。随着计算机技术、加密技术及图像处理技术的发展,出现了电子签章。电子签章是电子签名的一种表现形式,利用图像处理技术、数字加密技术将电子签名操作转化为与纸质文件盖章操作相同的可视效果,同时利用电子签名技术保障电子信息的真实性和完整性以及签名人的不可否认性

  • 2019-04-01 22:59:22

    Android Studio 3.0 利用cmake搭建jni环境(很详细哦)

    我用的Android Studio是3.0的版本,然后想搭建一下jni的环境。这里把自己遇到的问题和注意点都记录下。 首先是需要在android studio里面安装最基本的环境。 打开Default Preference里面查看SDK Tool选项。

  • 2019-04-01 23:20:58

    隐藏在图片中的密钥

    在客户端开发的时候,有时需要把密钥保存在本地。这时就会遇到密钥安全性的问题。要保证密钥安全性,无非就是混淆、隐藏、白盒等手段。本文以隐藏在图片中来阐述密钥的安全保存。

  • 2019-04-01 23:22:33

    验证数字签名

    应预先设置验证首选项。在打开 PDF 后显示包含签名的验证详细信息时,这有助于确保数字签名有效。有关详细信息,请参阅设置签名验证首选项。