Python笔记:接口测试Requests

1.简介

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

2.下载

pip install requests

3.引用

import requests

4.请求方式

GET:

import requests


# requests.get()方法发送的是GET请求,因此不需要设置data参数,应该使用params参数来传递请求参数,params=

response = requests.get('https://www.baidu.com')
 # 响应状态码: 200
print('响应状态码:', response.status_code) 

# 请求网络地址 https://www.baidu.com/
print('请求网络地址:', response.url)  

# 请求头信息 {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 28 Mar 2022 13:01:40 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:23:55 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
print('请求头信息:', response.headers) 
 
# cookie信息 <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
print('cookie信息', response.cookies)  

# 设置编码 防止乱码
response.encoding = 'utf-8' 

# 文本的形式打印
print(response.text) 


POST:

import requests    # 导入网络请求模块requests
import json        # 导入json模块

# requests.post()方法发送的是POST请求,因此需要设置data参数,json=


# 登录获取token
def login():
    # url
    url = "http://127.0.0.1:8888/login"
    # 请求头类型
    header = {"Content-Type": "application/json"}
    # 请求参数
    data = {
        "code": 1,
        "password": 123456,
        "username": "xxx"
    }
    # 发送post接口请求获取响应结果并转为json格式后提取token
    try:
        res = requests.post(url=url, headers=header, json=data)
        response = res.json()
        response_token = response['data']
        token = response_token['access_token']
        print(token)
    except Exception as e:
    print("获取Token失败:", str(e))


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值