python用requests實現http請求程式碼例項
阿新 • • 發佈:2020-01-09
這篇文章主要介紹了python用requests實現http請求過程解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
1. get
import requests # 最簡單的get請求 r = requests.get(url) print(r.status_code) print(r.json()) # url 中?key=value&key=value r = requests.get(url,params=params) # form 表單 params = {"username":"name","password":"passw0rd"} headers = {'Content-Type':'application/x-www-form-urlencoded'} r = requests.get(url,params=params,headers=headers) # 下載 r = requests.get(url) r.raise_for_status() with open(target,'wb') as f: for ch in r.iter_content(10000): result_file_size += f.write(ch)
2. post請求
data = {'name':'train','device':'CN0989'} r = requests.post(url,json=data) #上傳 files = { "file": (os.path.basename(filepath),open(filepath,"rb"),"application/zip") } print('POST %s'%url) with open(filepath,'rb') as f: r = requests.post(url,files=files)
3. 登入
_session = requests.Session() # login url = '%s/login'%_basic_url params = {"username":"admin","password":"admin"} headers = {'Content-Type':'application/x-www-form-urlencoded'} r = _session.post(url,headers=headers) #做其他請求 r = _session.get(url) _session.close()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。