网络编程

1 import urllib.request
2 import json,requests
3 url='http://api.nnzhp.cn/api/user/stu_info?stu_name=test'
4 url='http://api.nnzhp.cn/api/user/stu_info?stu_name=小黑马'
5 
6 res=urllib.request.urlopen(url)#发送请求
7 jieguo=res.read().decode()#获取结果
8 print(json.loads(jieguo))

发送get请求:

1 url='http://api.nnzhp.cn/api/user/stu_info?stu_name=wxc_陈萌'
2 req=requests.get(url)#发送get请求
3 print(req.text)#获取结果,json串
4 print(type(req.text))
5 print(json.loads(req.text))#转成字典形式
6 print(req.json())#获取结果就是字典,必须返回的是json串,才能用.json()方法

发送post请求:

1 url='http://api.nnzhp.cn/api/user/login'
2 data={'username':'niuhanyang','passwd':'aA123456'}
3 req=requests.post(url,data)#发送post请求,第一个参数是url,第二个参数是请求的数据
4 print(req.json())
5 print(req.text)

注册接口:

1 url='http://api.nnzhp.cn/api/user/user_reg'
2 data={''username':'weixiaoxiao','pwd':'12345Qa','cpwd':'123'}
3 re1=requests.post(url,data)
4 print(req.json())

入参是json:

url='http://api.nnzhp.cn/api/user/add_stu'
data={'name':'weixiaocui','grade':'巨蟹座','phone':31971891234}
req=requests.post(url,json=data)#发送post请求,第一个参数是url,第二个参数是请求的数据
print(req.json())
print(req.text)

 添加cookie:

1 url='http://api.nnzhp.cn/api/user/gold_add'
2 data={'stu_id':231,'gold':1000}
3 cookie={'niuhanyang':'6d195100b95a43046d2e385835c6e2c2'}
4 req=requests.post(url,data,cookie=cookie)
5 print(req.json())

添加header:

1 url='http://api.nnzhp.cn/api/user/all_stu'
2 mpp={'Referer':'http://api.nnzhp.cn/','User-Agent':'Chore'}
3 res=requests.get(url,headers=mpp)
4 print(res.json())

上传文件:

1 url='http://api.nnzhp.cn/api/file/file_upload'
2 f=open(r'C:\Users\bjniuhanyang\Desktop\ad.cpm.schedulingInfo.v1.json','rb')
3 r=requests.post(url,files={'file':f})
4 print(r.json())

下载文件:

1 url='http://www.besttest.cn/data/upload/201710/f_36b1c59ecf3b8ff5b0acaf2ea42bafe0.jpg'
2 r=requests.get(url)
3 print(r.status_code)#获取请求的状态码
4 print(r.content)#获取返回结果二进制格式的
5 fw=open(r'bt.jpg','wb')
6 fw.write(r.content)
7 fw.close()

保存网页(简单的爬虫):

1 url='http://www.nnzhp.cn/archives/630'
2 r=requests.get(url)
3 f=open('nnzhp.html','wb')
4 f.write(r.content)
5 f.close()

 

posted @ 2018-02-01 10:55  飞鸟与新月  阅读(529)  评论(0编辑  收藏  举报