python中使用requests模塊http請求時,發(fā)現(xiàn)中文參數(shù)不會自動的URL編碼,并且沒有找到類似urllib (python3)模塊中urllib.parse.quote("中文")手動URL編碼的方法.研究了半天發(fā)現(xiàn)requests模塊對中文參數(shù)有3種不同的處理方式.
一、requests模塊自動URL編碼參數(shù)
要使參數(shù)自動URL編碼,需要將請求參數(shù)以字典的形式定義,如下demo:
import requestsproxy = {"http":"http://127.0.0.1:8080", "https":"http://127.0.0.1:8080"}def reTest(): url = "http://www.baidu.com" pdict = {"name":"中文測試"} requests.post(url = url,data = pdict,proxies = proxy)效果如下圖,中文被URL編碼正確處理

二、參數(shù)原樣輸出,不需要編碼處理
使用dictionary定義參數(shù),發(fā)送請求時requests模塊會自動URL編碼處理參數(shù).但有些時候可能不需要編碼,要求參數(shù)原樣輸出,這個時候?qū)?shù)直接定義成字符串即可.
import requestsproxy = {"http":"http://127.0.0.1:8080", "https":"http://127.0.0.1:8080"}def reTest(): url = "http://www.baidu.com" pstr1 = "name=中文".encode("utf-8") requests.post(url = url,data = pstr1, proxies = proxy)注:參數(shù)需要utf-8編碼,否則會報錯Use body.encode('utf-8') if you want to send it encoded in UTF-8.
最后效果如下圖,參數(shù)原樣輸出:

三、參數(shù)使用format或%格式化,導(dǎo)致參數(shù)str變成bytes
有些時候直接定義的字符串參數(shù),其中有的參數(shù)是變量,需要format或%格式化控制變量.這個時候會發(fā)現(xiàn)格式化后的參數(shù)變成了bytes.
import requestsproxy = {"http":"http://127.0.0.1:8080", "https":"http://127.0.0.1:8080"}def reTest(): url = "http://www.baidu.com" pstr2 = "name={0}".format("中文".encode("utf-8")) requests.post(url = url,data = pstr2, proxies = proxy)參數(shù)變成了bytes

在該種請求下:
1. 如果參數(shù)需要URL編碼.當(dāng)參數(shù)少的時候可以使用dict定義.如果參數(shù)太多,dict比較麻煩,可以針對參數(shù)使用urllib.parse.quote("中文")手動encode成URL編碼.
2. 如果中文參數(shù)需要原樣輸出.將參數(shù)格式化完成后再編碼即可.pstr2 = "name={0}".format("中文").encode("utf-8")
以上這篇對python中使用requests模塊參數(shù)編碼的不同處理方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點(diǎn)
疑難解答
圖片精選