python--网络编程requests

时间:2024-04-16 08:37:14

一、requests

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

1.发送get请求

 url ='http://IP/api/user/stu_info'
data = {'stu_name':'小黑'}#请求数据
req = requests.get(url,params=data)#发get请求
print(req.json())#返回的是个字典
print(req.text)#返回的是json串 string类型

2.发送post请求

 url ='http://IP/api/user/login'
data = {'username':'niuhanyang', 'passwd':'aA123456'}#请求数据
req = requests.post(url,data)#发送post请求
print(req.json())

3.入参是json类型的

 import random
url='http://IP/api/user/add_stu'
phone =random.randint(10000000000,99999999999)
data = {
"name":"ytt",
"grade":"天蝎座",
"phone":phone,
"sex":"女",
"age":28,
"addr":"河南省济源市北海大道32号"
}
req = requests.post(url,json=data)#指定入参json
print(req.json())#.json()方法获取的结果直接是一个字典

4.添加cookie

 url= 'http://IP/api/user/gold_add'
data ={'stu_id':468,'gold':1000}
cookie ={'niuhanyang':'337ca4cc825302b3a8791ac7f9dc4bc6'}
req = requests.post(url,data,cookies=cookie)#使用cookies参数指定cookie
print(req.json())

5.添加header

 url ='http://IP/api/user/all_stu'
header ={
'Referer':'http://api.nnzhp.cn/'
}
req = requests.get(url,headers=header)#指定headers参数,添加headers
print(req.json())

6.上传文件、图片

 url ='http://api.nnzhp.cn/api/file/file_upload'
# data = {
# 'file':open('ytt.txt',encoding='utf-8')
# }#上传文件
data = {
'file':open(r'C:\Users\yantiantian\Desktop\ytt.png','rb')
}#上传图片
req = requests.post(url,files=data)#指定files参数,传文件,是一个文件对象
print(req.json())

7.下载文件

 url ='http://r.photo.store.qq.com/psb?/V11Xu0l62tE9ZU/YkT0cPNTMfGUHhTbTwB7*bZEySWaXvK1BlaRD3GGMgc!/r/dKzoe.WwLQAA&.jpg'
req = requests.get(url)
print(req.content)#返回的二进制的
fw = open('ytt.jpg','wb')
fw.write(req.content) #下载mp3
url2 ='http://up.mcyt.net/?down/46779.mp3'
req = requests.get(url)
print(req.content)#返回的二进制的
fw = open('ytt.mp3','wb')
fw.write(req.content)