import urllib.request
import json,requests
url = 'http://api.nnzhp.cn/api/user/stu_info?stu_name=test'
url2 = 'http://api.nnzhp.cn/api/user/stu_info?stu_name=小黑马'
res=urllib.request.urlopen(url)#发送请求
result=res.read().decode()#获取结果,返回类型是bytes,decode编程字符串,如果请求中stu_name=小黑马,中文会报错
print(json.loads(result))#字符串再编程json
发送get请求
req=requests.get(url2)#发送get请求
print(req.text)#获取结果
print(type(req.text))#<class 'str'>
print(json.loads(req.text))#把字符串转为字典,字典是单引号,json是双引号
print(req.json())#获取结果直接就是字典,必须返回的是json串,才能用.json方法
print(type(req.json()))#<class 'dict'>
发送POST请求
url="http://api.nnzhp.cn/api/user/login"
data={'username':'niuhanyang','passwd':'aA123456'}
req=requests.post(url,data)#发送post请求,第一个参数是url,第二个参数是请求的数据
print(req.json())
url_register='http://api.nnzhp.cn/api/user/user_reg'
data={'username':'panliye','pwd':'Panliye1988','cpwd':'Panliye1988'}
req=requests.post(url_register,data)
print(req.json())
url_login='http://api.nnzhp.cn/api/user/login'
data={'username':'panliye','passwd':'Panliye1988'}
req_login=requests.post(url_login,data)
#入参是json
url="http://api.nnzhp.cn/api/user/add_stu"
data={'name':'panliye','grade':'双子座','phone':18900090001}
req=requests.post(url,json=data)#发送post请求,第一个参数是url,第二个参数是请求的数据
print(req.json())
添加header
url='http://api.nnzhp.cn/api/user/all_stu'
ply={'Referer':'http://api.nnzhp.cn/'}
res=requests.get(url,headers=ply)
print(res.json())
添加cookie
url='http://api.nnzhp.cn/api/user/gold_add'
data={'stu_id':180,'gold':10000}
cookie={'niuhanyang':'6d195100b95a43046d2e385835c6e2c2'}
req=requests.post(url,data,cookies=cookie)
print(req.json())
#上传文件
url='http://api.nnzhp.cn/api/file/file_upload'
f=open(r'C:\Users\Administrator\Desktop\pic.png','rb')
r=requests.post(url,files={'file':f})
print(r.json())
下载文件
url='http://www.besttest.cn/data/upload/201710/f_36b1c59ecf3b8ff5b0acaf2ea42bafe0.jpg'
r=requests.get(url)
print(r.status_code)#获取请求的状态码 200是可以的
print(r.content)#获取返回结果二进制格式的
fw=open('bt.jpg','wb')
fw.write(r.content)
fw.close()
下载博客文件
url='http://www.nnzhp.cn/archives/630'
r=requests.get(url)
f=open('nnzhp.html','wb')
f.write(r.content)
f.close()