python requests 持久化 cookie 示例:

# -*- coding:utf-8 -*-

import json
import os

import requests

headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'X-Requested-With': 'XMLHttpRequest',
    'Referer': 'https://www.example.com/',
}


class Example:
    def __init__(self):
        self.session = requests.session()
        self.__load_cookies()

    def __del__(self):
        self.__save_cookies()

    def __load_cookies(self):
        if os.path.isfile('cookies.txt'):
            with open('cookies.txt', 'r') as f:
                self.session.cookies.update(json.load(f))

    def __save_cookies(self):
        with open('cookies.txt', 'w') as f:
            f.write(json.dumps(self.session.cookies.get_dict()))

    def check_status(self):
        url = 'https://account.example.com/api/getLoginInfo'
        response = self.session.get(url, headers=headers)
        result = response.json()
        if result.get('status') != 1:
            return False
        return True

    def login_account(self, username, password):
        url = 'https://account.example.com/account/submitLogin'
        data = {
            'uname': username,
            'pwd': password,
        }
        response = self.session.post(url, headers=headers, data=data)
        result = response.json()
        if result.get('status') != 1:
            return False
        return True

    def other_request(self):
        pass

session = requests.session() 返回一个 Session 会话对象,在复用该对象进行请求,会自动带上前一个请求生成的 cookie。

通过 json.dumps(session.cookies.get_dict()) 将 cookie 转换成字符串,保存到文件。下次启动程序时,再通过 session.cookies.update(json.load(f)) 还原之前的 cookie,这样有效的复用 cookie,在一些需要登录状态验证的场景中可以免去频繁的登录操作。