接口自动化

requests定义

requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到,Requests是Python语言的第三方的库,专门用于发送HTTP请求

requests响应

r.status_code 响应状态码
r.heards 响应头
r.cookies 响应cookies
r.text 响应文本
r. encoding 当前编码
r. content 以字节形式(二进制)返回

最常用的是根据响应状态码判断接口是否连通,经常用于做接口中断言判断

get请求

1.基本get请求的写法:

import requests

response = requests.get("http://httpbin.org/get")

print(response.text)

2.带参数的get请求(在链接的后面加上问号再加参数): 复制代码

Response = requests.get("http://httpbin.org/get?name=germey&age=22")

#还有一种方式:就是先定义一个字典,然后调用get方法的时候,将字典赋值给给params参数

data = {

‘name’:’germey’,

‘age’:22

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

print(response.text)

模块总览 dataDemo(存放数据)>> readDemo(读取数据) useRequests(发送请求)>>testDemo(生成报告)

基本post请求,和get请求类似

需要的表单数据也用一个字典存起来给data参数,headers和get方法一样

Import requests

headers = {

“User-Agent”:“Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36”

}

data = {

‘name’:’germey’,

‘age’:22

}

#需要注意和get方法不同的是如果有参数用的是data=而不是params=

response = requests.post(“https://www.zhihu.com/expiore”,data = data,headers = headers)

print(response.json())

将读取的数据存放到列表中

# 接口
url,params,methon
http://japi.juhe.cn/qqevaluate/qq,{"qq":"2962863689","key":"9aaf2d20b591e6e94edf97c1c64d290e"},post
http://apis.juhe.cn/mobile/get,{"phone":"13611130750","key":"e051969849556bb1bc1e19c73c813d52"},get
import csv
class Resd_Csv():
    def resd_csv(self):
        item = []
        r = csv.reader(open("../dataDemo/testdemo.csv","r"))
        # 循环获取csv中的数值,并添加到item中
        for i in r:
            item.append(i)
        # 获取下标值为 1 的值和他后面的数据
        item = item[1:]
        return item

r = Resd_Csv()
a = r.resd_csv()
print(a)

requests请求接口返回状态码,并使用断言

接口

url,params,methon
http://japi.juhe.cn/qqevaluate/qq1324,{“qq”:“2962863689”,“key”:“9aaf2d20b591e6e94edf97c1c64d290e”},post
http://apis.juhe.cn/mobile/get,{“phone”:“13611130750”,“key”:“e051969849556bb1bc1e19c73c813d52”},get

from readDemo.resd_csv import Read_Csv
import requests

r = Read_Csv()
aa = r.read_csv()
 print(aa)

class RequestsClass():
    def requests_method(self):
        item = []
        for j in aa:
            if j[2] == "get":
                rr = requests.get(url=j[0], params=j[1])
                item.append(rr.status_code)
            else:
                rr = requests.post(url=j[0], data=j[1])
                item.append(rr.status_code)
        return item

r = RequestsClass()
ee = r.requests_method()
print(ee)
from useRequests.requestsuse import RequestsClass
import pytest
 查看传过来的状态码是否正常
r = RequestsClass()
a = r.requests_method()
 print(a)
#创建一个类,进行断言
class TestClaa():
    def test_one(self):
        # 循环取出数据并进行断言
        for i in  a:
            assert i == 200
if __name__ == '__main__':
    pytest.main(["test_one.py"])

response属性

response = requests.post("https://www.jianshu.com")

print(type(response.status_code),response.status_code)

print(type(response.headers),response.headers)

print(type(response.cookies),response.cookies)

print(type(response.url),response.url)

print(type(response.history),response.history) 

状态码判断

1 response = requests.post("https://www.jianshu.com")
2 
3 exit() if not response.status_code==200 else print("request sucessfully")
4 
5 或者可以写成:
6 
7exit() if not response.status_code==request.codes.ok else print("request sucessfully")

状态码和request.codes列表中的英文状态对应表

状态码

英文

100

(“continue”,)

101

(“switching_protocols”)

102

(“processing”,)

103

(“checkpoint”,)

122

(“url_too_long”,“request_url_too_long”)

200

(“ok”,“okay”,“all_ok”,“all_good”,\o/,“√”)

201

(“created”,)

202

(“accepted”,)

203

(“non_authoritative_info”,“non_authoritative_information”)

204

(“no_content”,)

205

(“reset_content”,“reset”)

206

(“partial_content”,“partial”)

207

(“multi_status”,“multiple_status”,“multi_stati”,“multiple_stati”)

208

(“already_reported”,)

300

(“multiple_choices”,)

301

(“moved_permanentiy”,“moved”,"\o-")

302

(“found”,)

303

(“see_other”,“other”)

304

(“not_modified”)

305

(“use_proxy”)

306

(“switch_proxy”)

307

(“temporary_redirect”,“remporary_moved”,“temporary”)

308

(“permanent_redirect”,“resume_incomplete”,“resume”)

400

(“bad_request”,“bad”)

401

(“unauthorized”,)

402

(“payment_required”,“payment”)

403

(“forbidden”,)

404

(“not_found”,"-o-")

405

(“method_not_allowed”,“not_allowed”)

406

(“not_acceptable”,)

407

(“proxy_authentication_required”,“proxy_auth”,“proxy_authentication”)

408

(“request_timeout”,“timeout”)

409

(“conflict”,)

410

(“gone”,)

411

(“length_required”,)

412

(“precondition_falled”,“precondition”)

413

(“request_entity_too_large”,)

414

(“request_uril_too_large”,)

415

(“unsupported_media_type”,“unsupported_media”,“media_type”)

416

(“requested_range_not_satisfiable”," requested_range"," range_not_satisfiable")

417

(“expectation_failed”,)

418

(“im_a_teapot”,“teapot”,“i_am_a_teapot”)

421

(“misdirected_request”,)

422

(“unprocessable_entity”,“unprocessable”)

423

(“locked”,)

424

(“failed_dependency”,“dependency”)

425

(“unordered_collection”,“unordered”)

426

(“upgrade_required”,“upgrade”)

428

(“precondition_required”,“precondition”)

429

(“too_many_requests”,“too_mary”)

431

(“header_fields_too_large”," fields_too_large")

444

(“no_response”,“none”)

449

(“retry_with”,“retry”)

450

(“unavallable_for_legal_reasons”,“parental_controls”)

451

(“unavallable_for_legal_reasons”,“legal_reasons”)

499

(“client_closed_request”,)

500

(“internal_server_error”,“server_error”,"/o\",“×”)

501

(“not_implemented”,)

502

(“bad_gateway”,)

503

(“service_unavaliable”,“unavaliable”)

504

(“gateway_timeout”)

505

(“http_version_not_supported”,“http_version”)

506

(“variant_also_negotiates”,)

507

(“insufficient_storage”,)

509

(“bandwidth_limit_exceeded”,“bandwidth”)

510

(“not_extended”,)

511

(“network_authentication_required”,“network_auth”,“network_authentication”)

request的高级操作

1 import requests
2 
3 files = {"file":open("test.png",'rb')}
4 
5 response = requests.post("http://httpbin.org/post",files=files)   #需要用post方法
6 
7 print(response.text)

text返回的files是一个文件字节流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值