python-requests模块(get,post)

一、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': '[email protected]'
}
timeout = 0.5
requests.get(url, headers=header, params=param, timeout=timeout)  # 发get请求

二、post

  1、与get方法类似,设置好对应的参数,就可以了。举个栗子:

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

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

  2、接口的返回值:

    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

猜你喜欢

转载自www.cnblogs.com/lilyo/p/11989689.html