您的位置:首页 > 编程语言 > Python开发

python使用requests模块参数编码的不同处理

2017-02-27 22:37 309 查看
python中使用requests模块http请求时,发现中文参数不会自动的URL编码,并且没有找到类似urllib (python3)模块中
urllib.parse.quote("中文")
手动URL编码的方法.研究了半天发现requests模块对中文参数有3种不同的处理方式.

一、requests模块自动URL编码参数

要使参数自动URL编码,需要将请求参数以字典的形式定义,如下demo:

import requests

proxy = {"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编码正确处理



二、参数原样输出,不需要编码处理

使用dictionary定义参数,发送请求时requests模块会自动URL编码处理参数.但有些时候可能不需要编码,要求参数原样输出,这个时候将参数直接定义成字符串即可.

import requests

proxy = {"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)


注:参数需要utf-8编码,否则会报错
Use body.encode('utf-8') if you want to send it encoded in UTF-8.


最后效果如下图,参数原样输出:



三、参数使用format或%格式化,导致参数str变成bytes

有些时候直接定义的字符串参数,其中有的参数是变量,需要format或%格式化控制变量.这个时候会发现格式化后的参数变成了bytes.

import requests

proxy = {"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)


参数变成了bytes



在该种请求下:

1. 如果参数需要URL编码.当参数少的时候可以使用dict定义.如果参数太多,dict比较麻烦,可以针对参数使用
urllib.parse.quote("中文")
手动encode成URL编码.

2. 如果中文参数需要原样输出.将参数格式化完成后再编码即可.
pstr2 = "name={0}".format("中文").encode("utf-8")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python url 编码 requests