将cookies保存到文件(python版)

import json
import os
import requests
from requests.cookies import RequestsCookieJar


def save_cookie():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
    }
    url = "http://www.test.com"
    session = requests.session()
    cookieJar = getcookies_decode_to_dict()
    response = session.get(url, headers=headers, cookies=cookieJar)
    cookies = session.cookies.get_dict()
    path = os.getcwd() + '/cookies/'
    with open(path + 'cookies.txt', 'a+') as f:
        f.write(json.dumps(cookies))
        f.close()

    print(response.content.decode('utf-8'))


def getcookies_decode_to_dict():
    path = os.getcwd() + '/cookies/'
    if not os.path.exists(path):
        print('Cookie文件不存在,请先运行cookiesload.py')
    else:
        cookies_dict = {}
        with open(path + 'cookies.txt', 'r') as f:
            js = f.read()
            if not js:
                return
            cookies = json.loads(js)
            return cookies
            for cookie in cookies:
                cookies_dict[cookie['name']] = cookie['value']
            return cookies_dict


def getcookies_decode_to_cookiejar():
    path = os.getcwd() + '/cookies/'
    if not os.path.exists(path):
        print('Cookie文件不存在,请先运行cookiesload.py')
    else:
        cookiejar = RequestsCookieJar()
        with open(path + 'cookies.txt', 'r') as f:
            cookies = json.loads(str(f.read()))
            for cookie in cookies:
                cookiejar.set(cookie['name'], cookie['value'])
            return cookiejar


save_cookie()

你可能感兴趣的:(将cookies保存到文件(python版))