

headers字符串转字典 并储存在headers.json 复制到剪贴板-Python程序-效果演示
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.

headers字符串转字典 并储存在headers.json 复制到剪贴板-Python程序-效果演示
# -*- 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()
Recommend
-
97
JavaScript复制内容到剪贴板
-
32
-
28
每日前端夜话 第332篇 翻译: 疯狂的技术宅 作者:Sanwar ranwa 来源:dzone 正文共:1376 字 预...
-
15
最近的项目上需要做复制粘贴相关的操作,来总结下吧 复制、剪切、粘贴事件: copy 发生复制操作时触发;cut 发生剪切操作时触发;paste 发生粘贴操作时触发;每个事件都有一个 before 事件对应:befo...
-
7
阿航 2020年5月30日
-
13
需求如下:将index.txt 的内容进行格式转换后复制到剪贴板。index.txt莲子心中苦,梨儿腹内酸。--明末清初.金圣叹 雨入花心,自成甘苦。水归器内,各现方圆。--明末清初.金圣叹 真读书人天下少,不...
-
3
Python爬虫编程思想(77): XML字符串转换为字典 ...
-
6
Python爬虫编程思想(78): JSON字符串与字典互相转换 ...
-
7
通过 ssh 登录到远程机器后,想要复制远程机器的文件内容是一件很麻烦的事情。 通过拖动来复制对于多行的内容很难实现精确定位,还有可能会遇到换行符的问题。利用 clipper 命令可以很方便地复制远程机器的内...
-
16
Python中字典转换成字符串的3种方法 - 迷途小书童的Note迷途小书童的Note 迷途小书童的Note >
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK