贴一篇自己写的HEADER处理脚本

发布于 2023-08-26  379 次阅读


  • 上一篇提到有些api或者页面的访问是需要伪造header的,但是浏览器直接复制出来的header并不符合python里面字典的格式,这里用脚本快速改格式.

代码实现

  • 通过上一篇的方法,从控制台中复制出来的header的格式是这样的
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding:
gzip, deflate, br
Accept-Language:
zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
Cache-Control:
max-age=0
Connection:
keep-alive
Host:
drinkflower.asia
If-Modified-Since:
Tue, 27 Jun 2023 04:39:16 GMT
Sec-Ch-Ua:
"Microsoft Edge";v="119", "Chromium";v="119", "Not?A_Brand";v="24"
Sec-Ch-Ua-Mobile:
?0
Sec-Ch-Ua-Platform:
"Windows"
Sec-Fetch-Dest:
document
Sec-Fetch-Mode:
navigate
Sec-Fetch-Site:
none
Sec-Fetch-User:
?1
Upgrade-Insecure-Requests:
1
User-Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.2109.1
  • 最后我们要得到的格式是这样的
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'Accept-Encoding':'gzip, deflate, br',
'Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Host':'drinkflower.asia',
'If-Modified-Since':'Tue, 27 Jun 2023 04:39:16 GMT',
'Sec-Ch-Ua':'"Microsoft Edge";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
'Sec-Ch-Ua-Mobile':'?0',
'Sec-Ch-Ua-Platform':'"Windows"',
'Sec-Fetch-Dest':'document',
'Sec-Fetch-Mode':'navigate',
'Sec-Fetch-Site':'none',
'Sec-Fetch-User':'?1',
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.2109.1',
  • 用手一点一点改就太麻烦了,可以通过下面的脚本直接改,把原始的信息输入header.txt,执行之后,规范的格式将会生成在本目录下的newheader.txt中,都是一些简单的正则和字符串操作
import time
file=open('header.txt',"a+",encoding="utf-8")
file.seek(0)
lines=file.readlines()
if(len(lines)%2!=0):
    print("存在某个或多个字段的值为空,请手动删除该字段\n待程序运行结束后,再重新添加到程序的运行结果中")
    time.sleep(10000)
for i in range(len(lines)):
    if(i%2!=0):
        lines[i]="'"+lines[i].replace("\n","")+"',\n"
    else:
        lines[i]="'"+lines[i][0:-2]+"':"

nlines=[]
for i in range(len(lines)-1):
    if(i%2==0):
        #print(i)
        nlines.append(lines[i].replace("\n","")+lines[i+1])

file.close()
file=open('newheader.txt',"w",encoding="utf-8")
file.writelines(nlines)
  • 不过有一些也不是很常见就暂时没有处理的bug,比如有的header长这样
Accept:
*/*
Accept-Encoding:
gzip, deflate, br
Accept-Language:
zh-CN,zh;q=0.9
Sec-Ch-Ua-Mobile:
?0
Sec-Ch-Ua-Platform:
"Windows"
Sec-Fetch-Dest:
empty
Sec-Fetch-Mode:
cors
Sec-Fetch-Site:
same-origin
User-Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36
X-Ab-Param:
X-Ab-Pb:
CgQnB/gMEgIAAA==
  • 里面存在X-Ab-Param:这种没有值的空行,会导致后面的行全部错位,就需要手动删除了,因为这个字段的值是空的,加不加也没有什么用.
届ける言葉を今は育ててる
最后更新于 2024-02-07