python-requests模块

一、get

1、url格式:http://接口地址?key1=value1&key2=value2

2、get方法,有几个常用的参数:

url:接口的地址

headers:定制请求头(headers),例如:content-type = application/x-www-form-urlencoded

params:用于传递测试接口所要用的参数,这里我们用python中的字典形式(key:value)进行参数的传递。

timeout:设置接口连接的最大时间(超过该时间会抛出超时错误)

3、举个例子

import requests
# 请求数据
url = 'http://api.shein.com/v2/member/login'
header = {
    'content-type': 'application/x-www-form-urlencoded'
}
param = {
    'user_id': '123456',
    'email': '123456@163.com'
}
timeout = 0.5
requests.get(url, headers=header, params=param, timeout=timeout)  # 发get请求

二、post

1、post方法简单使用:

带数据的post,带header的post,带json的post,带参数的post,普通文件上传,定制化文件上传,多文件上传

2、方法定义:requests.post(url,data=None,json=None,**kwargs)。举个栗子:

import requests
# 请求数据
url = 'http://api.shein.com/v2/member/login'
header = {
    'content-type': 'application/x-www-form-urlencoded'
}
data = {
    'user_id': '123456',
    'email': '123456@163.com'
}
timeout = 0.5
req = requests.post(url, headers=header, data=data, timeout=timeout)  # 发post请求
print(req.text)
print(type(req.json()))

post方法中的参数,我们不在使用params进行传递,而是改用data进行传递了

3、实战1:使用data传递参数,返回值正常

url = 'https://app-item.daydaycook.com.cn/kill/helpkKill'
data = {
    'killPriceGroupId': '1268',
    'platform': '4',
    'sessionId': 'ee1edff9-b756-40e9-91d5-2753cfff0457',
    'token': 'F1A2AA2B6BE386091E929FD433C683D9'
}
req = requests.post(url, data=data)  # 发post请求
print(req.text)

4、实战2:使用data传递参数,报400

url = 'https://backend-web-t1.daydaycook.com.cn/backend/credit/sendCredit.jhtml'
data = {
    'userId': '1611412',
    'content': '111',
    'description': '222',
    'department': '333'
}
req = requests.post(url, data=data)  # 发post请求
print(req.text)

解决办法:改用json传递参数

url = 'https://backend-web-t1.daydaycook.com.cn/backend/credit/sendCredit.jhtml'
data = {
    'userId': '1611412',
    'content': '111',
    'description': '222',
    'department': '333'
}
req = requests.post(url, json=data)  # 发post请求
print(req.text)

5、文件上传,使用files传递参数

import requests

url = 'https://backend-web-t1.daydaycook.com.cn/backend/credit/readEvent.jhtml'
cookies = {
    'AUTHORITY.SESSIONID': 'BE8D72F515C0209BE574A7EED421F9CBBD6D26D5A5C3C3AA1E556CB6'
}
files = {
    'file': open('/Users/ddcuser/Downloads/credit_issue.xlsx', 'rb')
}
req = requests.post(url, cookies=cookies, files=files)  # 发post请求
print(req.text)

6、接口的返回值:

text:获取接口返回值的文本格式

json():获取接口返回值的json()格式

status_code:返回状态码(成功为:200)

headers:返回完整的请求头信息(headers['name']:返回指定的headers内容)

encoding:返回字符编码格式

url:返回接口的完整url地址

三、注意

关于失败请求抛出异常,我们可以使用“raise_for_status()”来完成,那么,当我们的请求发生错误时,就会抛出异常。如果你的接口,在地址不正确的时候,会有相应的错误提示(有时也需要进行测试)这时,千万不能使用这个方法来抛出错误,因为python自己在链接接口时就已经把错误抛出,那么,后面你将无法测试期望的内容。而且程序会直接在这里宕掉,以错误来计。  

def get(self):
    try:
        response = requests.get(self.url, params=self.params, headers=self.headers, timeout=float(timeout))
        # response.raise_for_status()
        return response
    except TimeoutError:
        self.logger.error("Time out!")
        return None
原文地址:https://www.cnblogs.com/lilyo/p/11989689.html