python+requests实现接口测试 - get与post请求使用(转载)

转自:http://www.cnblogs.com/nizhihong/p/6567928.html

简介:Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。更重要的一点是它支持 Python3 哦!

一、安装

使pip安装:

pip install requests

安装完后,运行一个简单的例子查看是否安装成功:

1
2
3
4
5
import  requests                                  #导入requests包
r = requests.get(url = 'https://www.baidu.com/' )   
print (r.status_code)                             #查看请求返回的状态
#结果
200

  

二、几种请求类型

  ①get请求:requests.get('url') 

  ②post请求:requests.post("url/post")

  ③put请求:requests.put("url/put")

  ④delete请求:requests.delete("url/delete")

  ⑤head请求:requests.head("url/get")

  ⑥options请求:requests.options("url/get")

三、get请求

传递url参数

在get请求中,允许使用params关键字,以一个字典来传递这些参数,例如:

1
2
3
4
5
6
7
content = { 'pageIndex' : 1 , 'pageSize' : 10 , 'categoryId' : 9 }  
r = requests.get( 'http://www.xxxxx.com/api/v2/activities' ,params = content)
print  (r.url)                        #获取请求内容
print  (r.text)                       #获取响应内容
#结果
http: / / www.xxxx.com / api / v2 / activities?pageIndex = 1 &pageSize = 10 &categoryId = 9
{ "data" :[], "pageIndex" : 1 , "totalNum" : 0 , "hasMore" :false, "pageSize" : 0 }

如果字典中存在None的值,是不会添加到url请求中的

1
2
3
4
5
6
content = { 'pageIndex' : 1 , 'pageSize' : 10 , 'categoryId' : None }  
r = requests.get( 'http://www.xxxxx.com/api/v2/activities' ,params = content)
print  (r.url)                     
 
#结果
http: / / www.xxxx.com / api / v2 / activities?pageIndex = 1 &pageSize = 10

  

ps:不使用params的话,也可在请求中输入全部的地址,效果相同,如:

r=requests.get('http://m.xxxxx.com/api/v2/activities?pageIndex=1&pageSize=10&categoryId=9')

注意:在某些get请求中,需要辨别用户身份,因此会需要在请求中发送cookie内容,如某些需要用户登录才能访问的页面,相关内容请轻戳这里

四、post请求

1.以表单形式传递参数:

想要发送一些表单形式的数据,只需简单的传递一个字典给data关键字,在发送请求的时候,会自动编码为表单的形式,例如:

1
2
content = { 'key1' : 'value1' , 'key2' : 'value2' }
r = requests.post( 'http://www.xxx/api/v1/user/login' ,data = content)

2.以json形式传递参数:

在很多情况下,想要发送的数据并非为表单形式,而是一个json格式的字符串,如果传递给data关键字的内容不是一个dict,而是

一个string,那么在发送的时候,数据会被直接发送出去,不会自动编码为表单形式。

为了将一个数据结构转换为json格式的字符串,首先得需要导入一个json包,两种常用的方法为:json.dumps()与json.loads()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import  json
content = { 'name' : 'Nee' , 'age' : '18' }
str_content = json.dumps(content)       #把dick编码为json格式的字符串
print  (str_content)
print  ( type (str_content))
#结果:
{ "name" "Nee" "age" "18" }
< class  'str' >                         #此时的类型为str
 
content = json.loads(str_content)       #把json格式的字符串解码为原先的数据结构
print  (content)
print  ( type (content))
#结果
{ 'name' 'Nee' 'age' '18' }
< class  'dict' >

注意:1.json编码支持的基本类型有:None, bool, int, float, string, list, tuple, dict。对于字典,json会假设key是字符串(字典中的任何非字符串key都会在编            码时转换为字符串),要符合JSON规范,应该只对python列表和字典进行编码。此外,在WEB应用中,把最顶层对象定义为字典是一种标准做法。                    2.json编码的格式几乎和python语法一致,略有不同的是:True会被映射为true,False会被映射为false,None会被映射为null,元组()会被映射为列表[],如:

1
2
3
4
5
6
content = { 'a' : None , 'b' : True , 'c' : False , 'd' :( 1 , 2 )}
str_content = json.dumps(content)
print  (str_content)
 
#结果:
{ "a" : null,  "b" : true,  "c" : false,  "d" : [ 1 2 ]}

因此 想要在post请求中使用data关键字来传递json格式的字符窜,首先得把dict转为string,例如:

1
2
3
4
5
6
7
8
9
import  requests
import  json
url = 'http://www.xxx.com/api/v1/user/login'
data = { "ua" : "13700002000" , "pw" : "12qwaszx" , "ct" : 12 }
r = requests.post(url,data = json.dumps(data))          #在一些post请求中,还需要用到headers部分,此处未加,在下文中会说到  
print  (r.text)
 
#结果
{ "newUser" :false, "user" :{ "userId" : 531 , "mobileNo" : "13700002000" , "userName" : "测试用户2000" .......}

除了可以对dick编码后以string的方式传递参数外,还可以直接使用json关键字直接传递,在传递时会自行进行编码为string类型

1
2
3
4
import  requests             #不需要导入json模块
url = 'http://xxxx/api/v1/user/login'
data = { "ua" : "13700002000" , "pw" : "12qwaszx" , "ct" : 12 }
r = requests.post(url,json = data)

在post请求中用到的cookie部分。先关内容还是轻戳这里 

五、定制headers

若想要为请求添加头部信息,只需要在请求中使用headers关键字传递一个字典即可

首先简单介绍下headers中的内容:

  Host:www.xxx.com                   指定请求资源的主机

  Accept:image/png,*/*,q=0.5                指定客户端接受哪些类型的响应内容

  Accept-Language:zh-CN,zh;q=0.8,en;q=0.6     客户端的操作系统语言,通常使用中文操作系统,属性值一般为zh-cn

  Accept-Encoding:gzip, deflate               客户端所能接受的编码规则或格式规范

  Referer:Referer':'http://xx.com/user/login.html?   可以理解为请求来源

  Connection:keep-alive               表示当client和server通信时对于长链接如何处理  

  cookies                       不解释...

  ....

查看请求中发出的请求头,可以使用如下方法:

1
2
3
4
5
6
import  requests
r = requests.post(url,data)
print (r.request.headers)       #查看发出的请求头
 
- - - - - 结果 - - - - -
{ 'User-Agent' 'python-requests/2.13.0' 'Accept-Encoding' 'gzip, deflate' 'Accept' '*/*' 'Connection' 'keep-alive' , <br> 'Content-Length' '49' 'Content-Type' 'application/json' }

  

定制headers请求如下:

1
2
3
4
5
6
import  requests
headers = { 'Accept' : '*/*'
          'Accept-Encoding' : 'gzip, deflate, sdch'
           ...
         }
r = requests.post(url,data,headers = headers)

  

六、响应

1.响应状态

在请求发送成功后,可以用status_code来查看相应状态(每个状态代表的具体意义不在此文介绍)

1
2
3
4
5
6
import  requests
r = requests.get(url)
print (r.status_code)
 
- - - - - 结果 - - - - -
200

2.响应内容

在上面的内容中,已经展示了用text来获取相应的内容,返回的内容为string

1
2
3
4
5
6
7
8
import  requests
r = requests.get(url)
print  (r.text)
print  ( type (r.text))        #查看返回内容的类型
 
- - - - - 结果 - - - - -
..........                  #返回的具体内容
< class  'str' >               #类型为string

除此之外,requests中也带有带有一个内置的json解码器,将返回的内容转换为dict

1
2
3
4
5
6
7
8
import  requests
r.requests.get(url)
print  (r.json())
print  ( type (r.json()))
 
- - - - - 结果 - - - - -
......
< class  'dict' >

那么通过json解码器转为dict后,想要查看到返回内容中某个具体参数的值,就比较方便啦!

3.响应内容编码格式

在获取响应内容的时候,可以使用r.encoding来查看相应内容的编码格式

1
2
3
4
5
6
import  requests
r = requests.get(url)
print (r.encoding)
 
- - - - - 结果 - - - - -
UTF - 8

也可以进行指定编码,当改变了编码方式是后,每次获取响应内容,都会使用新的编码方式

1
2
3
4
import  requests
r = requests.get(url)
r.encoding = 'ISO-8859-1'
print (r.text)

4.响应头内容

1
2
3
import  requests
r = requests.get(url)
print  (r.headers)

5.cookies

1
2
3
import  requests
r = requests.get(url)
print  (r.cookies)

七、设置超时时间

可以通过timeout来设置超时时间,如果在此时间内没有响应,会报错

1
2
import  requests
r = requests.get(url,timeout = 1 )

猜你喜欢

转载自www.cnblogs.com/bifeng/p/10878133.html
今日推荐