1 # import urllib #python自帶 發網絡請求的一個模塊 [不好用] 2 3 from urllib.request import urlopen 4 from urllib.parse import urlencode 5 import json 6 url = 'http://api.nnzhp.cn/api/user/stu_info' 7 d = {'stu_name':'礦泉水'} 8 req = urlopen(url,urlencode(d).encode()) #指定路徑和參數 9 #必須要先用urlencode把字典轉換成字符串,然后還要繼續轉成二進制 10 11 print(req.read().decode())#返回的是字符串 12 result = json.loads(req.read().decode()) #轉換成字典的形式 13 print(result) 14 15 #以上 不好用 僅限於 知道就ok 16 17 import requests 18 19 #get請求 20 url = 'http://api.nnzhp.cn/api/user/stu_info' 21 d = {'stu_name':'礦泉水'} 22 req = requests.get(url,d) 23 print(req.json())#返回的是字典 24 print(req.text) #返回的是字符串 25 26 #post請求 27 url = 'http://api.nnzhp.cn/api/user/login' 28 data = {'username':'niuhanyang','passwd':'aA123456'} 29 req = requests.post(url,data) 30 print(req.json()) 31 32 #傳cookie的方式 33 url = 'http://api.nnzhp.cn/api/user/gold_add' 34 data = {'stu_id': 6307,'gold':99} 35 cookie = {'niuhanyang':'d0378b2def134d736ae358121cf38ff0'} 36 req = requests.post(url,data,cookies=cookie) 37 print(req.text) 38 39 url = 'http://api.nnzhp.cn/api/user/gold_add' 40 data = {'stu_id': 6307,'gold':99} 41 cookie = {'niuhanyang':'d0378b2def134d736ae358121cf38ff0'} 42 cookie2 = {'cookie':'niuhanyang=d0378b2def134d736ae358121cf38ff0'} 43 # req = requests.post(url,data,cookies=cookie) 44 req = requests.post(url,data,headers=cookie2)#用headers的方法 45 print(req.text) 46 47 #用第二種headers的方式比較方便,因為cookie值有很多個的時候,用haeders直接復制就可以了 48 #但是用key->value的方式的話 要一個key一個value的寫進去 比價麻煩 49 50 #入參是json的 51 data = { 52 "name": "礦泉水222", 53 "sex": "未知", 54 "age": 38, 55 "addr": "天通苑", 56 "grade": "雙子座", 57 "phone": "15901211115", 58 "gold": 100 59 } 60 61 url = 'http://api.nnzhp.cn/api/user/add_stu' 62 req = requests.post(url,json=data) 63 print(req.text) 64 65 #上傳文件 66 url = 'http://api.nnzhp.cn/api/file/file_upload' 67 data = {'file':open('上傳文件用','rb')}#b代表二進制 68 req = requests.post(url,files = data) 69 print(req.text) 70 71 #下載 圖片/音樂 [網絡傳輸都是用二進制進行傳輸的] 72 url = 'http://aliuwmp3.changba.com/userdata/userwork/12107482.mp3' 73 req = requests.get(url) #只要能在瀏覽器里直接打開的都是get請求 74 with open('aqmm.mp3','wb') as fw: 75 print(req.content) #content 代表返回二進制的內容 76 fw.write(req.content) #返回的文件要存起來,返回的內容寫入文件 77 78 url = 'https://aliimg.changba.com/cache/photo/18189396_640_640.jpg' 79 req = requests.get(url) #只要能在瀏覽器里直接打開的都是get請求 80 with open('aqmm.jpg','wb') as fw: 81 print(req.content) #content 代表返回二進制的內容 82 fw.write(req.content) #返回的文件要存起來,返回的內容寫入文件