Python requests中params与data参数的区别详解
本文详细解析Python requests库中request()函数的params与data参数区别。通过GET和POST方法的实际案例,说明params用于URL查询字符串,而data用于请求正文。同时补充method、url及13个kwargs参数的完整用法,帮助开发者正确使用HTTP请求参数。
params与data参数的核心区别
示例代码如下:
import requests
url='http://www.baidu.com'
#下面使用requests.request(method, url, **kwargs)
re=requests.request('GET',url)

经测试,该方法是有效的。
我们尝试传入一个字典,首先使用params参数进行演示。

运行结果如下:

请注意url和args字段的变化。
接着使用get方法,将dic字典传递给data参数进行尝试。

结果依然体现在args和url中,令人意外的是,dic字典并未被传递进去。
原因如下:

params用于发送查询字符串,而data用于发送请求正文。post方法和get方法的特性在于:这两种参数在post方法中均可使用,但get方法只能发送查询字符串,无法发送正文。
接下来尝试使用post方法:

上述代码使用data参数传递字典,注意观察form字段。
再尝试使用params参数传递该字典:

结果体现在url和args中。
requests.request完整参数指南
补充知识:python_request_三个参数
requests.request(method,url,**kwargs)
method:请求方法,对应get/put/post/delete/head/patch/options
url: 模拟获取页面的url连接
**kwrags:控制访问的参数,共13个
kwargs(13个参数):
(一)params
params:字典或者字节序列,作为参数增加到url中
例子:
import requests
kv={“wd”:“你好”}#拼接的内容用字典储存
r=requests.request(“GET”,“http://www.baidu.com/s”,params=kv)
print(r.url)
print(r.text)
运行后拼接的效果:http://www.baidu.com/s?wd=你好
(二)data
data:字典、字节、或文件对象,作为request
例子:
import requests
kv={“key1”:“value1”,“key2”:“value2”}
r=requests.request(“POST”,“http://httpbin.org/post”,data=kv)
print(r.text)
运行结果:
{
“args”: {},
“data”: “”,
“files”: {},
“form”: {
“key1”: “value1”,
“key2”: “value2”
},
“headers”: {
“Accept”: “/”,
“Accept-Encoding”: “gzip, deflate”,
“Connection”: “close”,
“Content-Length”: “23”,
“Content-Type”: “application/x-www-form-urlencoded”,
“Host”: “httpbin.org”,
“User-Agent”: “python-requests/2.18.1”
},
“json”: null,
“origin”: “113.235.118.39”,
“url”: “http://httpbin.org/post”
}
(三)json
json:JSON格式的数据,作为request的内容
(四)header
header:字典,http定制头
例子:
import requests
hd={‘user-agent':“Chrome/10”}#改变浏览器模拟
r=requests.request(“post”,“http://www.baidu.com”,headers=hd
(五)cookies:
cookies:字典或CookieJar,request中的cookie
(六)auth
auth:元组,支持HTTP认证功能
(七)files:
files:字典类型,传输文件
(八)tiemout
timeout:设定时间
(九)proxies
proxies:字典类型,设定访问代理服务器,可以增加登录认证
以上这篇python requests包的request()函数中的参数-params和data的区别介绍就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













