文章目录
转载请注明原始出处: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