Python接口测试-requests库

一、requests库

Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。

二、发请求

response = requests.get(‘https://github.com/timeline.json’) #GET请求
response = requests.post(“http://httpbin.org/post”) #POST请求
response = requests.put(“http://httpbin.org/put”) #PUT请求
response = requests.delete(“http://httpbin.org/delete”) #DELETE请求
response = requests.head(“http://httpbin.org/get”) #HEAD请求
response = requests.options(“http://httpbin.org/get”) #OPTIONS请求

返回类型是一个HTTPresponse类型。

print(response.status_code)  # 打印状态码
print(response.url)          # 打印请求url
print(response.headers)      # 打印头信息
print(response.cookies)      # 打印cookie信息
print(response.text)  #以文本形式打印网页源码
print(response.content) #以字节流形式打印

三、传参

1、方法

(1)直接将参数放在url内

response = requests.get(http://httpbin.org/get?name=gemey&age=22)

(2)先将参数填写在dict中,发起请求时params参数指定为dict

data = {
    'name': 'tom',
    'age': 20
}

response = requests.get('http://httpbin.org/get', params=data)

2、为你的请求添加头信息

heads = {}
heads['User-Agent'] = 'Mozilla/5.0 ' \
                          '(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \
                          '(KHTML, like Gecko) Version/5.1 Safari/534.50'
 response = requests.get('http://www.baidu.com',headers=headers)

3、使用代理

 proxy = {
        'http': '120.25.253.234:812',
        'https' '163.125.222.244:8123'
    }
 req = requests.get(url,proxies=proxy)

4、不同于get请求,post请求可以在body里添加内容

data = {'name':'tom','age':'22'}

response = requests.post('http://httpbin.org/post', data=data)

5、异常捕获处理

import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestException

try:
    response = requests.get('http://www.baidu.com',timeout=0.5)
    print(response.status_code)
except ReadTimeout:
    print('timeout')
except HTTPError:
    print('httperror')
except RequestException:
    print('reqerror')

四、会话保持

会话对象让你能够跨请求保持某些参数。它也会在同一个 Session 实例发出的所有请求之间保持 cookie。

session = requests.Session()
session.get('http://httpbin.org/cookies/set/number/12345')
response = session.get('http://httpbin.org/cookies')

具体见

requests官方中文文档 

快速入门版 http://docs.python-requests.org/zh_CN/latest/user/quickstart.html 

进阶版 http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced

猜你喜欢

转载自blog.csdn.net/hellochristie/article/details/88761898