Python对URL编码和解码

在做接口测试时,时常会发现抓取的接口参数中含有这种数据:%3D%5B%7B%22mainspucode%22%3A%22SPU66668%22%2C%22mainskucode%22%3A%22536963999401508874

当请求数据为字典data = {k1:v1, k2:v2},且参数中包含中文或者?、=等特殊符号时,需要通过url编码,将data转化为特定格式k1=v1&k2=v2,并且将中文和特殊符号进行编码

 

from urllib import parse
from urllib import request

dict = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
data = parse.urlencode(dict)        # 将字典{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}转换为 k1=v1&k2=v2&k3=v3
print(data, '\n')


str = 'packagelist=%5B%7B%22mainspucode%22%3A%22SPU66668%22%2C%22mainskucode%22%3A%22536963999401508874%22%2C%22mainbarcode%22%3A%2266668%22%2C%22maincommodityname%22%3A%22%E8%8B%B9%E6%9E%9Ctest2%22%2C%22mainunitname%22%3A%22%E4%B8%AA%22%2C%22mainunitcode%22%3A%22003%22%2C%22lessspucode%22%3A%22SPU01180%22%2C%22lessskucode%22%3A%22540854222149648386%22%2C%22lessbarcode%22%3A%22Z190201000008%22%2C%22lesscommodityname%22%3A%22%E5%88%B6%E5%8D%95%E5%AD%904b%EF%BC%88%E5%B7%B2%E5%90%8C%E6%AD%A5%EF%BC%89%22%2C%22commoditytype%22%3A%2212%22%2C%22num%22%3A%2255%22%7D%5D'
str2 = parse.unquote(str)       # 解码字符串
print(str2)
str3 = parse.quote(str2)        # 对字符串进行编码
print(str3)

输出结果:

k1=v1&k2=v2&k3=v3
packagelist
=[{"mainspucode":"SPU66668","mainskucode":"536963999401508874","mainbarcode":"66668","maincommodityname":"苹果test2","mainunitname":"","mainunitcode":"003","lessspucode":"SPU01180","lessskucode":"540854222149648386","lessbarcode":"Z190201000008","lesscommodityname":"制单子4b(已同步)","commoditytype":"12","num":"55"}]
packagelist
%3D%5B%7B%22mainspucode%22%3A%22SPU66668%22%2C%22mainskucode%22%3A%22536963999401508874%22%2C%22mainbarcode%22%3A%2266668%22%2C%22maincommodityname%22%3A%22%E8%8B%B9%E6%9E%9Ctest2%22%2C%22mainunitname%22%3A%22%E4%B8%AA%22%2C%22mainunitcode%22%3A%22003%22%2C%22lessspucode%22%3A%22SPU01180%22%2C%22lessskucode%22%3A%22540854222149648386%22%2C%22lessbarcode%22%3A%22Z190201000008%22%2C%22lesscommodityname%22%3A%22%E5%88%B6%E5%8D%95%E5%AD%904b%EF%BC%88%E5%B7%B2%E5%90%8C%E6%AD%A5%EF%BC%89%22%2C%22commoditytype%22%3A%2212%22%2C%22num%22%3A%2255%22%7D%5D
posted on 2020-04-19 22:39  凌风子  阅读(3768)  评论(0编辑  收藏  举报