Requests库详解

目录

1、介绍及安装

2、使用requests发送get请求

2.1、使用requests发送不带参数的get请求

2.2、使用requests发送带参数的get请求

3、使用requests发送post请求

3.1、data参数提交数据

3.2、json参数提交数据

4、其他类型请求方法

5、响应内容解析

6、设置请求头

7、在请求头中添加cookie

8、利用session保持对话

9、文件上传下载

10、加密接口测试

11、接口参数关联


1、介绍及安装

        dos命令行安装: pip install requests  

        dos命令行验证: pip show requests

        pycharm导入requests

        从代码中导入:import requests

2、使用requests发送get请求

2.1、使用requests发送不带参数的get请求

        以访问百度为例,访问百度时,是使用的get请求,所以这里调用requests.get()方法,将返回结果用resp接收,这里因为响应结果是乱码,所以这里把返回结果编码设置为utf-8

import requests


def fun1():
    resp = requests.get("http://www.baidu.com")  #request发送不带参数的get请求
    resp.encoding="utf-8"        #防止中文乱码,设置响应内容编码格式
    print(resp.status_code)      #输出响应状态码
    print(resp.text)            #获取响应的文本信息

if  __name__ == "__main__":
    fun1()

2.2、使用requests发送带参数的get请求

        还是以访问百度为例,这里是在百度搜索python,后面增加了一个参数wd,也可以直接用

resp = requests.get("http://www.baidu.com/s?wd=python"),下面把url和请求参数分别用变量接受,在请求中使用变量,这种写法比较直观

#发送get请求带参数--请求格式为字典,使用params参数
def fun2():
    data_dict={"wd":"python"}
    req_url="http://www.baidu.com/s"
    resp = requests.get(url=req_url,params=data_dict)
    print(resp.status_code)

3、使用requests发送post请求

        post请求的参数分为两种情况,请求头中Content-type是application/x-www.form-url,后面的参数就是data,请求头中Content-type是application/json,参数就用json,

response = request.post(url,data=None,json=None)
param url : 请求的url
param data:(可选) 表单形式请求头中Content-type:application/x-www.form-url
param json:     (可选)    参数接收json数据时,Content-Type:application/json

说明: 

  • data:参数接收form表单数据,后台会自动附加form表单请求信息头

      header={"Content-Type":"application"}

  • json:参数接收json数据时,后台会自动附加json表单请求信息头

    header={“Content-Type”:“application/json”}

        随意抓取一个post请求接口,这个接口请求头中是Content-type:application/json,那么使用requests发送接口请求参数就用json。

3.1、data参数提交数据


        请求TPshop项目的登录接口  请求数据(username:13088888888 password:123456 verify_code:1234
        登录接口URL:http://localhost/index.php?m=Home&c=User&a=do_login请求头中Content-type:application/x-www.form-url

import requests

url_login = "http://localhost/index.php?m=Home&c=User&a=do_login"
login_data = {
    "username" :"15188888888",
    "password" : "6655342",
    "verify_code":"8888"
}
response = requests.post(url=url_login,data=login_data)
print(response.json())

3.2、json参数提交数据

  请求ihrm项目的登录接口   请求数据( "mobile" :"13800000002","password" : "123456")
  登录接口URL:http://ihrm-java.itheima.net/api/sys/login

import requests
url_login = "http://ihrm-java.itheima.net/api/sys/login"
#无论表单data还是json,都是用字典发送请求
login_json = {
    "mobile" :"13800000002",
    "password" : "123456"
}
response = requests.post(url=url_login,json=login_json)
#查看响应
print(response.json())

4、其他类型请求方法

        其他请求类型,比如:PUT、DELETE、HEAD以及OPTIONS

import requests

response = requests.put("http://www.baidu.com",data={"key":"value"})
response = requests.delete("http://www.baidu.com")
response = requests.head("http://www.baidu.com")(不常用)
response = requests.option("http://www.baidu.com")(不常用)

5、响应内容解析

         请求方法的返回值response为Response对象,我们可以从这个对象中获取所有我们想要的响应信息。

response.status_code  状态码
response.url		 请求url
response.encoding     查看响应头部字符编码
response.headers      头信息
response.cookies	  cookie信息
response.text		  文本形式的响应内容
response.content	  字节形式的响应内容
response.json()       JSON形式的响应内容

示例:

import requests
# 1). 访问百度首页的接口`http://www.baidu.com`,获取以下响应数据
response = requests.get("http://www.baidu.com")
# 2). 获取响应状态码
print("响应状态码",response.status_code)
# 3). 获取请求URL
print("请求url",response.url)
# 4). 获取响应字符编码
print("响应字符编码",response.encoding)
# 5). 获取响应头数据
print("响应头数据",response.headers)
#提取响应头数据中某个键的值
print("Content-Type",response.headers.get("Content-Type"))
# 6). 获取响应的cookie数据
print("cookie数据",response.cookies)
print("提取指定的cookie",response.cookies.get("BDORZ"))
# 7). 获取文本形式的响应内容
print("文本形式内容",response.text)
# 8). 获取字节形式的响应内容
print("响应内容",response.content)
print("响应内容",response.content.decode("utf-8"))

6、设置请求头

    如果需要为请求添加请求头数据,只需要传递一个字典类型的数据给 headers 参数就可以了,这里只是一个最简单例子示范,header有其他参数放在header变量即可。

"""
1. 请求IHRM项目的登录接口,URL: http://ihrm-java.itheima.net/api/sys/login
2. 请求头: Content-Type: application/json
3. 请求体: {"mobile":"13800000002", "password":"123456"}
"""
#设置请求头
import requests
url_login = "http://ihrm-java.itheima.net/api/sys/login"
#请求头是一个键值对
header  = {
    "Content-Type":"application/json"
}
login_data = {
    "mobile":"13800000002",
    "password":"123456"
}
response = requests.post(url=url_login,json=login_data,headers=header)
response.encoding = 'utf-8'
print(response.json())

7、在请求头中添加cookie

        我们在登录网站之后,浏览器上面都会保存以后cookie信息,我们在每次对网站发起请求都会带上,网站可以通过cookie对用户进行识别,如果在发送接口请求中没有带上cookie,网站将无法返回用户个人相关内容。

        这里以获取TPshop订单为例,通过验证码获取cookie信息,使用cookie做参数登录网站,然后在获取订单时,参数带上cookie

       1、通过验证码获取cookie 2、通过cookie登录进入网页 3、访问我的订单

# 相关接口: 获取验证码:http://localhost/index.php?m=Home&c=User&a=verify
# 登录:http://localhost/index.php?m=Home&c=User&a=do_login
# 我的订单:http://localhost/Home/Order/order_list.html
# 获取cookie数据: response.cookies
# 添加cookie数据: requests.post(url, cookies={"c1": "v1"})
import requests
response = requests.get("http://localhost/index.php?m=Home&c=User&a=verify")
print(response.cookies.get("PHPSESSID"))
url = "http://localhost/index.php?m=Home&c=User&a=do_login"
PHPSESSID = response.cookies.get("PHPSESSID")
cookies = {
    "PHPSESSID":PHPSESSID
}
json = {
    "username": "15188888888",
    "password": "6688342",
    "verify_code": "8888"
}
response = requests.post(url=url,json=json,cookies=cookies)
print(response.json())
#获取订单页面信息
response = requests.post("http://localhost/Home/Order/order_list.html",cookies=cookies)
print(response.text)

8、利用session保持对话

        每次访问,都要加上cookie信息,否则就无法保存会话信息,这里直接使用session实例,在一次获取之后,后续请求也能继续使用。调用获取验证码接口保存会话信息,然后登录,获取用户订单。

import requests
#创建session对象
session = requests.Session()
response = session.get("http://localhost/index.php?m=Home&c=User&a=verify")

#登录
login_url = "http://localhost/index.php?m=Home&c=User&a=do_login"
data = {
    "username": "15188888888",
    "password": "6688342",
    "verify_code": "8888"
}
response = session.post(url=login_url,json=data)
print(response.json())
response = session.post("http://localhost/Home/Order/order_list.html")
print(response.text)

9、文件上传下载


        如果文件上传还包含其他参数,就在post请求括号后面在加上data={k:v}或者json={k:v}内容

#r代表只读 b代表以二进制方式读取
def fun3():
    files = {
        'file':open('test.txt','rb')
    }
    req = requests.post(url="http://www.fanyunedu.com:5000/general/api/upload",files=files)
    print(req.text)

if  __name__ == "__main__":
    fun3()

文件下载

import requests
def fun4():

    req = requests.get("http://localhost:8080/tpshop/image/logo.png")
    with open('logo.png','wb') as f:
        f.write(req.content)
   
if  __name__ == "__main__":
    fun4()

10、加密接口测试

       这里用到的请求参数sign,是数据组合加密形式,获取sign值,首先查出uid、name、password、salt的值用特定格式,然后导入hashlib模块,使用md5加密,把加密后的结果作为参数。

def fun5():
    """加密接口请求"""
    uid,name,password,salt='3','qcj','123456','LZ7dYxCj5S68ucAh'
    import hashlib
    hl = hashlib.md5()
    hl.update('{}-{}-{}-{}'.format(uid,name,password,salt).encode('utf-8'))
    sigh = hl.hexdigest()#对hl对象中保存的字段进行md5的加密算法
    datas={"uid":"3","sign":sigh}
    url_data = "http://www.fanyunedu.com:5000/general/userinfo_sign"
    req = requests.post(url=url_data,json=datas)
    print(req.text)

11、接口参数关联

    

           用登录接口token和查询登录接口token,把上一个接口返回值用作下个结果参数

def fun6():

    datas = {
        "username":"qcj",
        "password":"123456"
    }
    login_url = "http://www.fanyunedu.com:5000/general/login_token"
    rep = requests.post(url=login_url,data = datas)
    req_json = rep.json()
    token =req_json['data']
    headers = {
        "auth-token":token
    }
    t_url="http://www.fanyunedu.com:5000/general/userinfo_token"
    t_req = requests.get(url=t_url,headers=headers)
    print(t_req.json())
if  __name__ == "__main__":
    fun6()

执行结果

{
    'code': 200,
    'data': {
        '用户id': 3,
        '用户姓名': 'qcj',
        '用户年龄': '18',
        '联系方式': '15888888888'
    },
    'msg': 'success'
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值