主要应用urllib和requests模块
urllib模块返回类型为bytes,需要数据类型转换;requests就方便很多。
例子1:发送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())
例子2:发送get请求
1 url = 'http://api.nnzhp.cn/api/user/stu_info?stu_name=小黑马' 2 req = requests.get(url) #发送get请求 3 print(req.text) #获取结果 4 print(req.json()) #获取结果直接就是字典,必须返回的是json串,才能用.json方法。
例子3:入参是json格式的
1 url = 'http://api.nnzhp.cn/api/user/add_stu' 2 data = {'name':'丁飞','grade':'巨蟹座','phone':31971891223} 3 req = requests.post(url,json=data) #发送post请求,第一个参数是url,第二个参数是请求的数据 4 print(req.json())
例子4:添加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,cookies=cookie) 5 print(req.json())
例子5:添加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())
例子6:上传文件
url = 'http://api.nnzhp.cn/api/file/file_upload' f = open(r'C:\Users\bjniuhanyang\Desktop\ad.cpm.schedulingInfo.v1.json','rb') r = requests.post(url,files={'file':f}) print(r.json())
例子7:下载文件
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()
例子8:保存网页
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()