Response Headers的转换

Response Headers的转换

​ 不知不觉一个月没有碰python了,今天看了点以前的东西发现都有点懵逼了。还行需要找点东西增强下记忆。

​ 今天写一个非常简单的实用型脚本。Response Headers转换。

​ 由于python脚本中的headers使用必须使用字典(dict)形式,所以这个小脚本实现了

  • chrome上的头部信息转字典
  • charles上的头部信息转字典

    使用python转换

从图中可以看出内容大致为

1
2
3
4
5
6
7
8
chrome:
xxx:xxx
xxx:xxx
xxx:xxx
charles:
xxx xxx
xxx xxx
xxx xxx

chrome中用 : 分开键值对

charles中用 \t 分开键值对

需要转换成为

1
2
3
4
{
'xxx':'xxx',
'xxx':'xxx'
}

行数少的时候自己手动转也还可以,但是行数一多就比较糟心了

先挑选一句进行转换xxx:xxx 转换为"xxx":"xxx",

1
2
3
4
5
6
s = 'xxx:xxx' #字符串
#chrome
s_list = s.strip().split(':') #['xxx','xxx']
#charles
s_list = s.strip().split('\t')#['xxx','xxx']
s_ok = "'" + "':'".join(s_list) + "',"

所以写成一个可以用的脚本就是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def change_headers(text):
text = text.strip()#去除首尾空格
text_list = text.splitlines()#按行切成list

for i in range(len(text_list)):#去除每行可能出现的空格
text_list[i] = text_list[i].strip()

if 'HTTP/1.1' in text_list[0]:#charls中的url信息_没啥用
text_list.pop(0)
if text_list[0].startswith('Host'):#因人而异的_基本没啥用
text_list.pop(0)
if text_list[-1].startswith('Cookie'):#一次性用品_没啥用
text_list.pop(-1)
if ':' in text_list[0]:
headers = "{\n " +
",\n ".join(map(lambda s:"'"+"':'".join(s.strip().split(':'))+"'",text_list))
+ "'\n}"
return headers
else:
headers = "{\n " +
",\n ".join(map(lambda s: "'" + "':'".join(s.strip().split('\t')) + "'", text_list))
+ "'\n}"
return headers
 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
您的支持将鼓励我继续创作!