python学习笔记(十八)网络编程之requests模块

有些话、适合烂在心里 提交于 2020-02-25 15:59:09

上篇博客中我们使用python自带的urllib模块去请求一个网站,或者接口,但是urllib模块太麻烦了,传参数的话,都得是bytes类型,返回数据也是bytes类型,还得解码,想直接把返回结果拿出来使用的话,还得用json,发get请求和post请求,也不通,使用比较麻烦,还有一个比较方便的模块,比urllib模块方便很多,就是requests模块,它使用比较方便,需要安装,pip install requests即可,下面是requests模块的实例

#1、发get请求
url = 'http://api.python.cn/api/user/stu_info'
data = {'stu_name':'小黑'}  #请求数据
req = requests.get(url,params=data)  #发get请求
print(req.json())  #返回数据是字典,但是要求必须返回的是json的时候,才能转为字典
print(req.text)    #返回数据是string,json串
#2 、发post请求url = 'http://api.python.cn/api/user/login'data = {'username':'test','passwd':'aA123456'}  #请求数据req = requests.post(url,data)  #发送post请求print(req.json())print(req.text)
#3、入参是json类型的import randomphone=random.randint(10000000000,99999999999)url='http://api.python.cn/api/user/add_stu'data =  {    "name":"小1",    "grade":"天蝎座",    "phone":phone,    "sex":"男",    "age":28,    "addr":"河南省济源市北海大道32号"  }req = requests.post(url,json=data)print(req.json())
# 4、添加cookieurl = 'http://api.python.cn/api/user/gold_add'data = {'stu_id':468,'gold':10000}djl = {'usertest':'337ca4cc825302b3a8791ac7f9dc4bc6'}req = requests.post(url,data,cookies=djl)print(req.json())
#5、添加headerurl = 'http://api.python.cn/api/user/all_stu'header = {    'Referer':'http://api.nnzhp.cn/'}req = requests.get(url,headers=header)print(req.json())
#6、上传文件url= 'http://api.python.cn/api/file/file_upload'data = {    'file':open(r'C:\Users\bjniuhanyang\Desktop\图\6bd9026dt935575932465&690.jpg','rb')}req= requests.post(url,files=data)print(req.json())
#7、下载文件url = 'http://up.mcyt.net/?down/46779.mp3'  #下载图片、MP3、MP4都是同样的操作,找到该资源的url即可req = requests.get(url)print(req.content)#返回的是二进制模式fw = open('aaa.mp3','wb')#二进制的文件写模式是"wb",读模式是"rb"fw.write(req.content)   #req.content返回的是bytes类型的
 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!