想要經過python來發送網絡請求,能夠使用內置的urllib2模塊python
可是requests模塊使用起來更簡潔 json
pip install requestsapi
一、發送get請求cookie
url1 = 'http://118.24.3.xx/api/user/stu_info' res = requests.get(url1,params={'stu_name':'xiaohei'})#發送get請求,params填寫參數 print(res.json())#返回數據是json,把結果轉爲字典
二、發送post請求網絡
url2 = 'http://118.24.3.xx/api/user/login' data = {"username":"niuhanyang","passwd":"aA123456"}#發送post請求,data填寫參數 res = requests.post(url2,data=data) print(res.json())
三、發送post請求,json傳參post
url3 = 'http://118.24.3.xx/api/user/add_stu' data = { "name":"requeslina", "grade":"天蠍座", "phone":18611532955, "sex":"男", "age":28, "addr":"河南省濟源市北海大道32號" } res = requests.post(url3,json=data)#post請求,json傳參 print(res.json())
四、帶cookies的請求url
url4 = 'http://118.24.3.xx/api/user/gold_add' data = {'stu_id':15,'gold':200} cookie = {'niuhanyang':'abd9a0995f4696e1a60133220b32037a'} res = requests.post(url4,data=data,cookies=cookie)#帶cookie的請求 print(res.json())#json直接把返回結果轉成字典
五、帶header的請求spa
url5 = 'http://118.24.3.xx/api/user/all_stu' header = {'Referer':'http://api.nnzhp.cn/'} res = requests.get(url5,headers=header)#帶header的請求 print(res.json())#json直接把返回結果轉成字典
六、字符串的響應數據code
url6 = 'http://www.nnzhp.cn' res = requests.get(url6) print(res.text)#字符串的響應數據
七、請求獲取二進制數據,能夠用來下載blog
url7 ='http://qiniuuwmp3.changba.com/1084511584.mp3' res = requests.get(url7) print(res.content)#獲取二進制的數據 with open('魔鬼中的天使.mp3','wb') as fw:#wb是寫二進制的東西 rb讀二進制的 fw.write(res.content) print(res.status_code)#響應狀態碼
八、下載一個圖片
url8 ='https://aliimg.changba.com/cache/photo/855e5493-f018-44db-8892-c8660649327b_640_640.jpg' res = requests.get(url8,verify=False)#若是是https 加verify=False參數 with open('lina.jpg','wb') as fw: fw.write(res.content)
九、上傳文件請求
url9 = "http://118.24.3.xx/api/file/file_upload" data = {'file':open('lina.jpg','rb')} res = requests.post(url9,files=data)#上傳文件 print(res.text)