Python中用post、get方式提交數(shù)據(jù)的方法示例
更新時間:2017年09月22日 10:43:24 作者:炎澤
最近在學(xué)習使用Python,發(fā)現(xiàn)網(wǎng)上很少提到如何使用post,所以下面這篇文章主要給大家介紹了關(guān)于Python中用post、get方式提交數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面來一起看看吧。
前言
最近在使用Python的過程中,發(fā)現(xiàn)網(wǎng)上很少提到在使用post方式時,怎么傳一個數(shù)組作為參數(shù)的示例,此處根據(jù)自己的實踐經(jīng)驗,給出相關(guān)示例,下面話不多說了,來一起跟著小編學(xué)習學(xué)習吧。
示例如下:
單純的post請求:
def http_post(): url = "http://152.1.12.11:8080/web" postdata = dict(d=2, p=10) post = [] post.append(postdata) req = urllib2.Request(url, json.dumps(post)) #需要是json格式的參數(shù) req.add_header('Content-Type', 'application/json') #要非常注意這行代碼的寫法 response = urllib2.urlopen(req) result = json.loads(response.read()) print result
需要token時寫法如下:
def http_post(): url = "http://152.1.12.11:8080/web" postdata = dict(d=2, p=10) post = [] post.append(postdata) req = urllib2.Request(url, json.dumps(post)) access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6I..........' req.add_header('Authorization', access_token) #header中添加token req.add_header('Content-Type', 'application/json') #要非常注意這行代碼的寫法 response = urllib2.urlopen(req) result = json.loads(response.read()) print result
get方式的寫法如下:
def get_access_token(): local_url = 'http://152.1.1.1:8080/web' response = urllib2.urlopen(local_url).read() resp = json.loads(response) print resp
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
python網(wǎng)絡(luò)爬蟲精解之Beautiful Soup的使用說明
簡單來說,Beautiful Soup 是 python 的一個庫,最主要的功能是從網(wǎng)頁抓取數(shù)據(jù),Beautiful Soup 提供一些簡單的、python 式的函數(shù)用來處理導(dǎo)航、搜索、修改分析樹等功能,需要的朋友可以參考下2021-09-09