吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 6060|回复: 25
收起左侧

[原创工具] 【Python】 GUI Headers格式化小工具

[复制链接]
1314271 发表于 2021-9-13 09:26
本帖最后由 1314271 于 2021-9-15 11:47 编辑

在学习爬虫的时候,经常会遇到需要自己复制headers手动打引号的蛋疼问题


于是就用tkinter写了这么一款gui小工具


可以把浏览器复制的headers直接转换为python字典格式


效果如下:
Snipaste_2021-09-15_11-38-49.png

感谢10楼@O_o 老哥,现使用python原生库json.dumps的indent属性添加缩进
给控件之间增加了边距,比之前美观了一些


转换后直接ctrl A + ctrl C 复制完然后就可直接粘贴到python代码里使用


下载链接:https://wwi.lanzoui.com/b01io8ugd    访问密码2333



代码如下:
[Python] 纯文本查看 复制代码
from tkinter import *
import tkinter.font
import json


class Header:
    def __init__(self):
        self.root = Tk()
        self.root['bg'] = "white"
        self.root.title("Headers格式化")
        self.root.geometry('640x310')
        self.root.resizable(0, 0)

        self.ft = tkinter.font.Font(family='微软雅黑', size=10, weight='normal', slant='roman', underline=0,)
        self.txt1 = tkinter.Text(self.root, relief="solid", wrap='none', font=self.ft)
        self.txt1.place(x=10, y=0, width=250, height=300)
        self.bind_menu(self.txt1)

        self.txt2 = tkinter.Text(self.root, relief="solid", wrap='none', font=self.ft)
        self.txt2.place(x=380, y=0, width=250, height=300)
        self.bind_menu(self.txt2)

        self.btn = tkinter.Button(self.root, text="转换>>", width=10, height=4, relief="groove", font=self.ft, command=self.format_str)
        self.btn.place(x=270, y=50, width=100, height=80)

        self.btn2 = tkinter.Button(self.root, text="清空", width=10, height=4, relief="groove", font=self.ft, command=self.clear)
        self.btn2.place(x=270, y=150, width=100, height=80)

        self.root.mainloop()

    def deal_str(self):
        data = {}
        lt = [x for x in self.txt1.get(1.0, "end").strip().split('\n') if x]
        for each in lt:
            i = each.index(":", 1) if each[0] == ":" else each.index(":")
            key = each[:i]
            word = each[i + 1:]
            if not word:
                word = ""
            key = key.strip()
            word = word.strip()
            data[key] = word
        return data

    def format_str(self):
        self.txt2.delete(0.0, "end")
        try:
            data = self.deal_str()
            if not data:
                return
        except:
            self.txt2.insert(END, "转换失败")
            return
        data = json.dumps(data, indent=4)
        self.txt2.insert(END, data)
        self.txt2.focus()
        return
        # text = "{\n"
        # for k, v in data.items():
        #     text += f"\t'{k}': '{v}',\n" if v != '""' else f"\t'{k}': '',\n"
        # text += "}"
        # self.txt2.insert(END, text)
        # self.txt2.focus()
        # return

    def bind_menu(self, editor):
        menubar = Menu(self.root, tearoff=False)

        def rightkey(event, editor):
            menubar.delete(0, END)
            menubar.add_command(label='复制(Ctrl + C)', command=lambda: editor.event_generate('<<Copy>>'))
            menubar.add_command(label='粘贴(Ctrl + V)', command=lambda: editor.event_generate('<<Paste>>'))
            menubar.add_command(label='剪切(Ctrl + X)', command=lambda: editor.event_generate("<<Cut>>"))
            menubar.add_command(label='全选(Ctrl + A)', command=lambda: editor.event_generate('<<SelectAll>>'))
            menubar.post(event.x_root, event.y_root)
        editor.bind("<Button-3>", lambda x: rightkey(x, editor))
        return

    def clear(self):
        self.txt1.delete(0.0, "end")
        self.txt2.delete(0.0, "end")
        return


if __name__ == '__main__':
    Header()


免费评分

参与人数 7吾爱币 +11 热心值 +7 收起 理由
jiangsg + 1 + 1 谢谢@Thanks!
kafei000 + 1 + 1 我很赞同!
Gem丶屈 + 1 + 1 谢谢@Thanks!
d8349565 + 1 这个网站使用起来很方便http://tool.yuanrenxue.com/curl
maxuxu2000 + 1 + 1 谢谢@Thanks!
PMM + 1 我很赞同!
风之暇想 + 7 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

wanpojie 发表于 2021-9-14 12:07
微信图片_20210914120046.png
O_o 发表于 2021-9-15 10:13
我改了一下,把cookie单独弄出来了.

微信图片_20210915101157.png
[Python] 纯文本查看 复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import json
from tkinter import *
import tkinter.font


def spawn_cookies(string):
    data = {}
    for line in string.split(';'):
        line = str(line).strip()
        if not line:
            continue
        chunk = line.split("=")
        k = chunk[0]
        v = "=".join(chunk[1:])
        if 'JSESSIONID' == k and k in data:
            continue
        data[k] = v
    return data


def spawn_headers(s):
    headers = {}
    cookies = {}
    ignore_keys = ['Content-Length']
    for line in s.split("\n"):
        line = line.strip()
        if not line:
            continue
        matched = re.match("^([a-zA-Z:\-]+):\s(.*?)$", line)
        if matched is None:
            raise ValueError("异常格式, line: %s" % line)
        name = matched.group(1)
        if name in ignore_keys:
            continue
        content = matched.group(2)
        if name.lower() == "cookie":
            cookies = spawn_cookies(content)
            continue
        headers[name] = content
    return headers, cookies


class Header:
    def __init__(self):
        self.root = Tk()
        self.root['bg'] = "white"
        self.root.title("Headers格式化")
        self.root.geometry('900x310')
        self.root.resizable(0, 0)

        self.ft = tkinter.font.Font(family='微软雅黑', size=10, weight='normal', slant='roman', underline=0, )
        self.txt1 = tkinter.Text(self.root, relief="solid", wrap='none', font=self.ft)
        self.txt1.place(x=10, y=0, width=250, height=300)
        self.bind_menu(self.txt1)

        self.txt2 = tkinter.Text(self.root, relief="solid", wrap='none', font=self.ft)
        self.txt2.place(x=380, y=0, width=250, height=300)
        self.bind_menu(self.txt2)

        self.txt3 = tkinter.Text(self.root, relief="solid", wrap='none', font=self.ft)
        self.txt3.place(x=640, y=0, width=250, height=300)
        self.bind_menu(self.txt3)

        self.btn = tkinter.Button(self.root, text="转换>>", width=10, height=4, relief="groove", font=self.ft,
                                  command=self.format_str)
        self.btn.place(x=270, y=50, width=100, height=80)

        self.btn = tkinter.Button(self.root, text="清空", width=10, height=4, relief="groove", font=self.ft,
                                  command=self.clear)
        self.btn.place(x=270, y=150, width=100, height=80)

        self.root.mainloop()

    def deal_str(self):
        data = {}
        lt = [x for x in self.txt1.get(1.0, "end").strip().split('\n') if x]
        for each in lt:
            i = each.index(":", 1) if each[0] == ":" else each.index(":")
            key = each[:i]
            word = each[i + 1:]
            if not word:
                word = ""
            key = key.strip()
            word = word.strip()
            data[key] = word
        print(data)
        return data

    def format_str(self):
        self.txt2.delete(0.0, "end")
        try:
            string = self.txt1.get(1.0, "end")
            headers, cookies = spawn_headers(string)
        except:
            self.txt2.insert(END, "转换失败")
            return
        str_headers = json.dumps(headers, sort_keys=True, indent=2)
        str_cookies = json.dumps(cookies, sort_keys=True, indent=2)
        self.txt2.insert(END, str_headers)
        self.txt3.insert(END, str_cookies)
        self.txt2.focus()
        return

    def bind_menu(self, editor):
        menubar = Menu(self.root, tearoff=False)

        def rightkey(event, editor):
            menubar.delete(0, END)
            menubar.add_command(label='复制(Ctrl + C)', command=lambda: editor.event_generate('<<Copy>>'))
            menubar.add_command(label='粘贴(Ctrl + V)', command=lambda: editor.event_generate('<<Paste>>'))
            menubar.add_command(label='剪切(Ctrl + X)', command=lambda: editor.event_generate("<<Cut>>"))
            menubar.add_command(label='全选(Ctrl + A)', command=lambda: editor.event_generate('<<SelectAll>>'))
            menubar.post(event.x_root, event.y_root)

        editor.bind("<Button-3>", lambda x: rightkey(x, editor))
        return

    def clear(self):
        self.txt1.delete(0.0, "end")
        self.txt2.delete(0.0, "end")
        self.txt3.delete(0.0, "end")
        return


if __name__ == '__main__':
    Header()

大罗金仙 发表于 2021-9-14 02:43
头像被屏蔽
hwxq43 发表于 2021-9-14 04:26
提示: 作者被禁止或删除 内容自动屏蔽
weilai911 发表于 2021-9-14 10:31
这个确实很实用 我每次都是一行一行复制
余律师 发表于 2021-9-14 10:39
多谢楼主分享!
v20471188 发表于 2021-9-14 10:47
感谢分享。
ptmaliang 发表于 2021-9-14 19:24
多谢楼主分享
五散倾尽 发表于 2021-9-15 09:49
感谢大佬分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 提醒:禁止复制他人回复等『恶意灌水』行为,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-14 18:12

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表