本帖最后由 话痨司机啊 于 2023-3-3 00:29 编辑
源码:
[Python] 纯文本查看 复制代码 '''
decs:headers 解析
date:2023年3月3日
author:话痨司机啊
---------------------------------
#### ex:
Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: X-Log, X-Reqid
Access-Control-Max-Age: 2592000
Age: 32250
Cache-Control: public, max-age=31536000
Content-Disposition: inline; filename="simditor.min.css"; filename*=utf-8''simditor.min.css
Content-Encoding: gzip
Content-Transfer-Encoding: binary
Content-Type: text/css
Date: Wed, 01 Mar 2023 15:44:44 GMT
ETag: "Fq0k2xlUKeux0jOY_wLkd036Cer2"
Last-Modified: Sun, 12 Feb 2017 15:33:30 GMT
Ohc-Cache-HIT: hg2un62 [2], wzix97 [2]
Ohc-File-Size: 10362
Ohc-Global-Saved-Time: Wed, 01 Mar 2023 06:46:26 GMT
Server: JSP3/2.0.14
Timing-Allow-Origin: *
Vary: Accept-Encoding
X-Cache-Status: HIT
X-Log: X-Log
X-Qiniu-Zone: 0
X-Reqid: S3YAAABJe5U9j_oW
X-Svr: IO
### ofter(dict):
{ 'Accept-Ranges':'bytes',
'Access-Control-Allow-Origin':'*',
...
}
----------------------------------
'''
import json
from pathlib import Path
class ParseHeader():
def __init__(self,str_headers:list,sign:bool):
self.str_headers = str_headers
self.headers = {}
self.pares_headers()
if sign:self.save_file
self.out_print()
def pares_headers(self):
for str_line in self.str_headers:
k,v = str_line.strip().split(':',1)
self.headers[k.strip()] = v.strip().replace('"',"'")
def save_file(self):
with open('headers_dict.txt','w',encoding='utf8') as f:
f.write(json.dumps(self.headers))
def out_print(self):
print(self.headers)
def check_print():
print('说明:选择1在命令行下粘贴headers,选择2,请在(h.txt)文件中粘贴headers:')
print('-'*60)
print('请选择1 or 2!:')
wrtie_in = input()
assert wrtie_in
return int(wrtie_in)
def init_print_and_run(num_int,try_num=3):
if try_num>=0:
if num_int == 1:
headers = input('请输入headers:')
headers_list = headers.splitlines()
yn = input('是否将其保存为文件headers_dict.txt(Y/N)')
if yn.lower() == 'y' and len(yn.lower())>0:
ParseHeader(headers_list,True)
elif yn.lower() == 'n' and len(yn.lower())>0:
ParseHeader(headers_list,False)
else:
init_print_and_run(try_num-1)
elif num_int ==2:
filename = 'h.txt'
with open(filename,'w+',encoding='utf8') as f:
read_list = f.readlines()
if len(read_list)>0:
yn = input('是否将其保存为文件headers_dict.txt(Y/N)')
if yn.lower() == 'y' and isinstance(yn,str):
ParseHeader(headers_list,True)
elif yn.lower() == 'n' and isinstance(yn,str):
ParseHeader(headers_list,False)
else:
init_print_and_run(try_num-1)
else:
f.write(' ')
raise ValueError('请输入headers后再运行此程序')
else:
print('重试次数已用尽,请重新运行!')
def main():
num = check_print()
if num == 1 or num ==2:
init_print_and_run(num)
else:
print('输入数字错误’)
if __name__ == "__main__":
main()
将图片里的文字格式转换为字典,方便requests的headers的使用。 |