2

headers字符串转字典 并储存在headers.json 复制到剪贴板-Python程序-效果演示

 2 years ago
source link: https://segmentfault.com/a/1190000040773528
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

headers字符串转字典 并储存在headers.json 复制到剪贴板-Python程序-效果演示

发布于 今天 03:53

代码效果演示
Gitee源码

# -*- coding: utf-8 -*-
# Version: Python 3.9.7
# Author: TRIX
# Date: 2021-10-05 13:51:29
# Use:将复制的请求标头字符串 转换成 headers字典 并储存在headers.json 复制到剪贴板

#使用方法:f12-网络-f5-名称-任意一个条目-标头-请求标头-复制所有-运行该文件

import pyperclip,json
def getHeaders(noKeys=None,extraStripChars=[':'],doPrint=False,):
    '''noKeys 根据键名去除键值对 键名与键名间以一个space分割 区分大小写 忽略是否strip

    extraStripChars 额外strip键名的无关字符 字符与字符间以一个space分割

    doPrint 是否打印headers和去除的键值对 只有在初次创建headers.json有用'''
    strs=pyperclip.paste()#读取剪贴字符串
    headers={}

    if 'Mozilla' not in strs:#如果复制字符串不是请求标头
        try:
            with open('headers.json','r',encoding='utf-8') as f:#读取储存的headers
                headers=json.loads(f.read())#json文本转dict对象
        except FileNotFoundError:
            return print('请至少完整复制一次请求标头信息\n复制方法:f12-网络-f5-名称-任意一个条目-标头-请求标头-复制所有')

    if not headers:
        def stripChars(word):#strip键名的无关字符
            word=word.strip()
            for char in extraStripChars:
                word=word.strip(char)
            return word

        keysValues=[]
        for keyOrValue in strs.split(': '):#以: 和\n切分字符串
            for kOrV in keyOrValue.split('\r\n'):
                keysValues.append(stripChars(kOrV))

        for i in range(0,len(keysValues),2):#生成headers字典
            headers[keysValues[i]]=keysValues[i+1]

        if noKeys:#去除指定键值对
            popKvs=[]
            for key in noKeys.split():
                popKvs.append(f"'{key}':'{headers.pop(stripChars(key))}'")

        headersJson=json.dumps(headers,ensure_ascii=False,indent=2)#dict对象转json文本 ensure_ascii让输出结果是中文而不是unicode indent缩进字符个数 值只能是 dict list int float str bool None
        with open('headers.json','w',encoding='utf-8') as h:#储存json数据
            h.write(headersJson)
        print('headers信息已储存至headers.json 并复制到剪贴板')

        if doPrint:#打印
            print('headers={')
            for k,v in headers.items():
                print(f"'{k}':'{v}',")
            print('}')
            if popKvs:
                print('\n去除headers的键值对如下:')
                for kv in popKvs:
                    print(kv)
                print('\n')

    pyperclip.copy(headersJson)#复制headers到剪贴板
    return headers

#getHeaders(noKeys='path',doPrint=True)
getHeaders()


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK