heaven123

python网络编程-requests模块

首先需要安装requests模块:pip install requests

# print(res.json())#必须返回的是json才可以用
# print(res.text)#返回的是字符串
# print(res.content)#返回的是二进制的,用来下载文件用的
# print(res.cookies)#获取到返回的所有cookie
# print(res.headers)#获取到返回的所有header
print(res.status_code)#获取状态码

import requests
#发送get请求
url='http://118.24.3/api/user/stu_info'
res=requests.get(url,params={'stu_name':'niuhanyang'})#发送get请求
print(res.json())#直接把结果转成字典
#发送post请求
url='http://118.24.3/api/user/login'
data={'username':'niuhanyan','passwd':'aA123456'}
res=requests.post(url,data=data)#发送post请求
print(res.json())
#post请求入参是json类型的
url2='http://118.24.3/api/user/add_stu'
data= {
"name":"小白",
"grade":"天蝎座",
"phone":15110002211,
"sex":"男",
"age":28,
"addr":"河南省济源市北海大道32号"
}
res=requests.post(url2,json=data)#post请求入参是json类型的
print(res.json())
#有cookie参数
url3='http://118.24.3/api/user/gold_add'
data={'stu_id':14693,'gold':100}
cookie={'niuhanyang':'f2ecc464c98850af1b6648d88a4ccae0'}
res=requests.post(url3,data=data,cookies=cookie)
print(res.json())
#有headers
url4='http://118.24.3/api/user/all_stu'
header={'Referer':'http://api.nnzhp.cn/'}
res=requests.get(url4,headers=header)
print(res.json())
# 打开网页
url5='http://www.cnblogs.com/jingw/'
res=requests.get(url5)
print(res.text)#返回的是字符串
#返回的二进制:歌曲,图片
url6='http://172.168.0.102:9999/upscuw.changba.com/934036130.mp3'
res=requests.get(url6)
print(res.content)#返回的是二进制
with open('后来.mp3','wb') as fw:
fw.write(res.content)

url7='https://aliimg.changba.com/cache/photo/855e5493-f018-44db-8892-c8660649327b_640_640.jpg'
res=requests.get(url7,verify=False)#如果是https要加上verify=False
with open('pic.jpg','wb')as fw:#二进制用wb
fw.write(res.content)

#上传文件
url8='http://118.24.3/api/file/file_upload'
file={'file':open('pic.jpg','rb')}
res=requests.post(url8,files=file)
print(res.json())

posted on 2019-07-23 12:51  heaven123  阅读(203)  评论(0编辑  收藏  举报

导航