Requests模块接口测试学习

安装方式

方式一:

执行 pip install -U requests 联网安装requests
pip install -U reqiests
方式二:
Requests模块接口测试学习 
2.然后用cmd进入解压目录,使用命令Python setup.py install 安装requests
Requests模块接口测试学习

 模拟get请求

import requests
response = requests.get(‘http://www.hnxmxit.com‘)

如果想在控制台看到访问结果,可使用

# 方法一
print(response.content.decode(‘utf-8‘))

# 方法二
print(response.text)

备注:方法二会有乱码,原因是因为response.text返回的是Unicode格式,通常需要转换为utf-8格式

response.encoding = ‘utf-8‘
print(response.text)

模拟带参数的get请求

import requests

# 方式1:将参数写入url地址
response_01 = requests.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET")
print(response_01.content.decode(‘utf-8‘))
import requests

# 方式2:将传入参数携程字典,然后在放到requests.get("url",parameter_data)中
parameter_data = {
    ‘grant_type‘ : ‘client_credential‘,
    ‘appid‘ : ‘APPID‘,
    ‘secret‘ : ‘APPSECRET‘
}
#
response_02 = requests.get("https://api.weixin.qq.com/cgi-bin/token", parameter_data)
print(response_02.content.decode(‘utf-8‘))

模拟请求头

import requests

search_data = {"wd": "新梦想软测"}
header_info = {
    ‘User-Agent‘: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
    ‘Accept‘: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    ‘Accept-Encoding‘: "gzip, deflate, br",
    ‘Accept-Language‘: "zh-CN,zh;q=0.9",
}

response = requests.get(url="https://www.baidu.com", params=search_data, headers=header_info)
print(response.content.decode(‘utf-8‘))

备注:如果带请求头,必须按博主这样写requests.get(url=‘‘, params="", headers="")

模拟post请求

在python中,可以将每一个dict看成是一个json对象

json.jumps() -- 用于将字典形式的数据转化为字符串

json.loads() -- 用于将字符串形式的数据转化为字典

import json
import jsonpath
import requests

params_data = {
    "access_token": ‘34_2icB2gvMB_RKpvIBGFoHU5zbPZPj9XRnfZPBtg9BIv1PxQPe4ELw6uQ6cjMbXSvCpi9PKkkMvM4kAiWyAGdwgX4synUQMrB9GpwPwpqorlzXP-yT52TdJt8AmuwgV2607BLYmJKv_wOle7YGYYCaAAAOOS‘}
head_infos = {‘Content-Type‘: ‘application/json‘}
post_params_data = {"tag": {"id": 148, "name": "test00001"}}
response = requests.post(url="https://api.weixin.qq.com/cgi-bin/tags/update",
                         params=params_data,
                         data=json.dumps(post_params_data),
                         headers=head_infos)

print(response.content.decode(‘utf-8‘))

相关推荐