上篇博客中我们使用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()) #返回数据是字典 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)
原文地址:https://www.cnblogs.com/mululu/p/9050059.html
时间: 2024-12-17 12:18:00