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')

五、查看和发送Cookie

 

具体见

requests官方中文文档 

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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值