标签:json random pre soft 发送post请求 bsp 需要 _id phone
一、requests
之前使用python自带的urllib模块去请求一个网站或者接口,但是urllib模块太麻烦了,传参数的话,都得是bytes类型,返回数据也是bytes类型,还得解码,想把返回结果拿出来使用的话,还得用json,发get请求和post请求,也不通,使用比较麻烦,还有一个比较方便的模块,比urllib模块方便很多,就是requests模块,它使用比较方便,需要安装,pip install requests即可,下面是requests模块的实例
1.发送get请求
1 url =‘http://IP/api/user/stu_info‘ 2 data = {‘stu_name‘:‘小黑‘}#请求数据 3 req = requests.get(url,params=data)#发get请求 4 print(req.json())#返回的是个字典 5 print(req.text)#返回的是json串 string类型
2.发送post请求
1 url =‘http://IP/api/user/login‘ 2 data = {‘username‘:‘niuhanyang‘, ‘passwd‘:‘aA123456‘}#请求数据 3 req = requests.post(url,data)#发送post请求 4 print(req.json())
3.入参是json类型的
1 import random 2 url=‘http://IP/api/user/add_stu‘ 3 phone =random.randint(10000000000,99999999999) 4 data = { 5 "name":"ytt", 6 "grade":"天蝎座", 7 "phone":phone, 8 "sex":"女", 9 "age":28, 10 "addr":"河南省济源市北海大道32号" 11 } 12 req = requests.post(url,json=data)#指定入参json 13 print(req.json())#.json()方法获取的结果直接是一个字典
4.添加cookie
1 url= ‘http://IP/api/user/gold_add‘ 2 data ={‘stu_id‘:468,‘gold‘:1000} 3 cookie ={‘niuhanyang‘:‘337ca4cc825302b3a8791ac7f9dc4bc6‘} 4 req = requests.post(url,data,cookies=cookie)#使用cookies参数指定cookie 5 print(req.json())
5.添加header
1 url =‘http://IP/api/user/all_stu‘ 2 header ={ 3 ‘Referer‘:‘http://api.nnzhp.cn/‘ 4 } 5 req = requests.get(url,headers=header)#指定headers参数,添加headers 6 print(req.json())
6.上传文件、图片
1 url =‘http://api.nnzhp.cn/api/file/file_upload‘ 2 # data = { 3 # ‘file‘:open(‘ytt.txt‘,encoding=‘utf-8‘) 4 # }#上传文件 5 data = { 6 ‘file‘:open(r‘C:\Users\yantiantian\Desktop\ytt.png‘,‘rb‘) 7 }#上传图片 8 req = requests.post(url,files=data)#指定files参数,传文件,是一个文件对象 9 print(req.json())
7.下载文件
1 url =‘http://r.photo.store.qq.com/psb?/V11Xu0l62tE9ZU/YkT0cPNTMfGUHhTbTwB7*bZEySWaXvK1BlaRD3GGMgc!/r/dKzoe.WwLQAA&.jpg‘ 2 req = requests.get(url) 3 print(req.content)#返回的二进制的 4 fw = open(‘ytt.jpg‘,‘wb‘) 5 fw.write(req.content) 6 7 #下载mp3 8 url2 =‘http://up.mcyt.net/?down/46779.mp3‘ 9 req = requests.get(url) 10 print(req.content)#返回的二进制的 11 fw = open(‘ytt.mp3‘,‘wb‘) 12 fw.write(req.content)
标签:json random pre soft 发送post请求 bsp 需要 _id phone
原文地址:https://www.cnblogs.com/yttbk/p/9046194.html