49.[Python]使用requests包进行HTTP交互方法详解

转载请注明原始出处:http://blog.csdn.net/a464057216/article/details/52713945

后续此博客不再更新,欢迎大家搜索关注微信公众号“测开之美”,测试开发工程师技术修炼小站,持续学习持续进步。
在这里插入图片描述

简介

Python的HTTP包有urllib、urllib2、httplib等,但是都需要了解较多的HTTP原理才能编码,借助requests包可以在较高的抽象层次上完成HTTP交互过程的开发。安装requests使用pip install requests命令,requests包内嵌了urllib3,自动支持HTTP长连接、连接池等功能。

使用方法

requests支持HTTP的HEAD、GET、POST、PUT、OPTIONS、DELETE、PATCH等请求:

r = requests.options('http://localhost:5000/')
print "Options:", r.headers
r = requests.post('http://localhost:5000/', data={
   'name': 'mars'})
print "Post:", r.content
r = requests.put('http://localhost:5000/', data={
   'name': 'loo'})
print "Put:", r.content
r = requests.get('http://localhost:5000/')
print "Get:", r.content
r = requests.delete('http://localhost:5000/')
print "Delete:", r.content
r = requests.get('http://localhost:5000/')
print "Get:", r.content

变量r是一个requests.models.Response类型的响应对象,通过r可以得到HTTP响应的所有信息。

传递QUERY参数

在URI的query部分传递参数,可以直接按照标准放在URL字符串中(允许为同一个key赋值多个value):

r = requests.get('http://localhost:5000/?xx=bb&xx=cc')

也可以放在请求的params参数中:

params = {
   
    'xx': ['bb', 'cc'],
    'yy': None,
}
r = requests.get('http://localhost:5000/', params=params)
print "Request URL:", r.url

使用字典做参数时,对同一个key的多个value要放在列表中,如果某个key对应的值为None,则其不会放在query中。

定制请求头

为HTTP请求报文的头部添加内容,可以请求时为headers参数赋值:

r = requests.get('http://localhost:5000/', headers={
   "mars": "loo"})

填写cookie

cookie可以以字典的形式赋值给cookies参数:

cookies = {
   
    "name": "mars"
}

r = requests.post('http://localhost:5000/', cookies=cookies)

通过RequestsCookieJar对象可以设置cookie的域、path等信息:

jar = requests.cookies.RequestsCookieJar()
jar.set('username', 'mars', domain='httpbin.org', path='/cookies')
jar.set('password', 'loo', domain='httpbin.org', path='/else')
r = requests.get('http://httpbin.org/cookies', cookies=jar)
print r.text

如果是在localhost做实验,domain参数需要赋值为空字符串''

http://httpbin.org/cookies提供的服务是:如果请求包含cookie的话,会在响应体中回应cookie内容,所以上述代码返回:

{
   
  "cookies": {
   
    "username": "mars"
  }
}

因为password/else这个path,所以通过/cookies无法访问key为password的cookie项。

填充请求体

如果采用application/x-www-form-urlencoded格式发送HTTP请求,可以将请求内容放在data参数中。如果采用ap

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值