【7】Python网络请求:requests模块
上面讲过的urllib模块太麻烦了,还有一个比较方便的模块,就是requests模块,好用到你怀疑人生·^_^,一定要会哦
使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)
需要安装,pip install requests即可,下面是requests模块的实例。
import requests response = requests.get('http://www.baidu.com') print(response.status_code) # 打印状态码 print(response.url) # 打印请求url print(response.headers) # 打印头信息 print(response.cookies) # 打印cookie信息 print(response.text) #以文本形式打印网页源码 print(response.content) #以字节流形式打印
import requests # -----------------发送get请求:获取学生信息接口---------------- # 编写url和参数 url='http://api.nnzhp.cn/api/user/stu_info' data = {"stu_name":"xiaohei"}# 参数 # res = requests.get(url,data).text #text方法返回的是字符串格式的返回值 res = requests.get(url,data).json() #json方法返回的是字典格式的返回值 print(res) print(type(res)) # -----------------发送post请求:登录接口---------------- url = 'http://api.nnzhp.cn/api/user/login' data = {"username":"niuhanyang","passwd":"aA123456"}# 参数 res = requests.post(url,data).text # res = requests.post(url,data).json() print(res) print(type(res)) # -----------------发送post请求:添加学生信息(入参是josn)---------------- url = 'http://api.nnzhp.cn/api/user/add_stu' data = {"name":"xiaoyang","grade":"一班","phone":"15022221111"}# 参数 res = requests.post(url,json=data).json() print(res) # -----------------发送post请求:学生金币充值(有cookie和身份验证)---------------- # 需要先调用登录接口,拿到cookie # { # "error_code": 0, # "login_info": { # "login_time": "20200511204314", # "sign": "107f0790d967706f3b29646ae7cfb3cf", # "userId": 47749 # } # } # cookie中key为登录的用户名,value从登录接口中获取,登陆成功之后会返回sign cookie = {"niuhanyang":"107f0790d967706f3b29646ae7cfb3cf"} url = 'http://api.nnzhp.cn/api/user/gold_add' data = {"stu_id ":"1","gold":"10000"}# 参数 res = requests.post(url,data,cookies=cookie).text print(res) # -----------------发送post请求:获取所有学生信息(有header)---------------- url = 'http://api.nnzhp.cn/api/user/all_stu' header = {"Referer":"http://api.nnzhp.cn/"} res = requests.get(url,headers=header).text print(res) # -----------------发送post请求:上传文件---------------- url = 'http://api.nnzhp.cn/api/file/file_upload' res = requests.post(url,files={"file":open('user.xlsx','rb')}).json() #我的参数名是file,open的是要上传的路径 print(res)
小练习
import requests import jsonpath # 写一个方法并调用方法,请求接口,获取返回值,解析取sign def getSign(): url = 'http://api.nnzhp.cn/api/user/login' data = {"username":"niuhanyang","passwd":"aA123456"} res = requests.post(url,data).json() # print(res) # {'error_code': 0, # 'login_info': {'login_time': '20200512153621', 'sign': '15aa5e3feb36248ff25e9e85abc1a024', 'userId': 47749}} #三种获取方式 # sign = res.get("login_info").get("sign")#获取不到返回null # sign = res["login_info"]["sign"]# 获取不到报错 sign = jsonpath.jsonpath(res,'$..sign')# 适合复杂的接口,返回结果是列表,获取不到返回false print(sign) #调试,表示是当前文件运行 if __name__ == '__main__': getSign()