標籤:imp log 必須 pass agent bsp any stat 擷取
import urllib.requestimport json,requests#urlib模組,不常用url = ‘http://api.nnzhp.cn/api/user/stu_info?stu_name=小黑馬‘res=urllib.request.urlopen(url)jieguo=res.read().decode() #傳回值都是Byte類型,需要轉碼print(json.loads(jieguo))#發送get請求url = ‘http://api.nnzhp.cn/api/user/stu_info?stu_name=小黑馬‘req = requests.get(url) #發送get請求print(req.text) #擷取結果print(req.json()) #擷取結果直接就是字典,必須返回的是json串,才能用.json方法。#發送post請求url = ‘http://api.nnzhp.cn/api/user/login‘data = {‘username‘:‘niuhanyang‘,‘passwd‘:‘aA123456‘}req = requests.post(url,data) #發送post請求,第一個參數是url,第二個參數是請求的資料print(req.json())#入參是json的url = ‘http://api.nnzhp.cn/api/user/add_stu‘data = {‘name‘:‘丁飛‘,‘grade‘:‘巨蟹座‘,‘phone‘:31971891223}#傳的是字典req = requests.post(url,json=data) #發送post請求,第一個參數是url,第二個參數是請求的資料print(req.json())#添加cookieurl = ‘http://api.nnzhp.cn/api/user/gold_add‘data = {‘stu_id‘:231,‘gold‘:1000}cookie = {‘niuhanyang‘:‘6d195100b95a43046d2e385835c6e2c2‘}req = requests.post(url,data,cookies=cookie)print(req.json())#添加headerurl=‘http://api.nnzhp.cn/api/user/all_stu‘mpp = {‘Referer‘:‘http://api.nnzhp.cn/‘,‘User-Agent‘:‘Chore‘}res = requests.get(url,headers=mpp)print(res.json())#上傳檔案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())#下載檔案url= ‘http://www.besttest.cn/data/upload/201710/f_36b1c59ecf3b8ff5b0acaf2ea42bafe0.jpg‘r = requests.get(url)print(r.status_code) #擷取請求的狀態代碼print(r.content) #擷取返回結果二進位格式的fw = open(r‘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()
python學習筆記7-網路編程