Python對URL編碼和解碼

2022-06-16 09:00:07 字數 1810 閱讀 6083

在做介面測試時,時常會發現抓取的介面引數中含有這種資料:%3d%5b%7b%22mainspucode%22%3a%22spu66668%22%2c%22mainskucode%22%3a%22536963999401508874

當請求資料為字典data = ,且引數中包含中文或者?、=等特殊符號時,需要通過url編碼,將data轉化為特定格式k1=v1&k2=v2,並且將中文和特殊符號進行編碼

from urllib import

parse

from urllib import

request

dict =

data = parse.urlencode(dict) #

將字典轉換為 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=

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

使用python對url編碼解碼

對url進行編碼和解碼,python提供了很方便的介面進行呼叫。1.urllib.quote string safe 對字串進行編碼。引數 safe 指定了不需要編碼的字元 2.urllib.unquote string 對字串進行解碼 3.urllib.quote plus string safe...

使用python對url編碼解碼

url中的query帶有特殊字元 不是url的保留字 時需要進行編碼。當url中帶有漢字時,需要特殊的處理才能正確編碼,以下都只針對這種情形,當然也適用於純英文本元的url。1 url編碼 import urllib url 哈哈 url url.decode gbk replace print u...

js對url進行編碼和解碼

只有 0 9 a z 以及某些保留字,才能不經過編碼直接用於 url。例如 搜尋的中文關鍵字,複製 之後再貼上就會發現該url已經被轉碼。原理 對除ascii字母 數字 標點符號 以外的其他字元進行編碼。編碼 escape 結果 escape 張 結果 u5f20 解碼 unescape http ...