python調(diào)用api實(shí)例講解
我們?cè)谧鲎詣?dòng)化運(yùn)維的時(shí)候,經(jīng)常需要調(diào)用api中的接口,不過(guò)很多人不知道具體的調(diào)用方法,在學(xué)習(xí)python中的requests庫(kù)后,我們就可以很輕松的實(shí)現(xiàn)了。
1、說(shuō)明api接口調(diào)用是指使用python的requests庫(kù)進(jìn)行訪問(wèn),基本上是get或post請(qǐng)求,有些接口會(huì)加密,然后必須使用對(duì)方提供給我們的公鑰加密或解密,配上相應(yīng)的參數(shù)進(jìn)行訪問(wèn),我們所需要的數(shù)據(jù)在請(qǐng)求后的返回結(jié)果中,所看到的基本上都是json格式的解析,所以請(qǐng)求后可以使用requests自帶的json函數(shù)進(jìn)行解析,然后提取所需的數(shù)據(jù),訪問(wèn)一次就能得到一個(gè)數(shù)據(jù)。
2、實(shí)例# encoding: utf-8import requestsimport os,reimport urllib.request data={'email':'[email protected]', 'password':'ydd4903087'}session = requests.session()session.post('http://www.renren.com/PLogin.do',data= data,verify = False)response =session.get('http://www.renren.com/410043129/profile')print (response.text)print (response.url)print (response.status_code)print (response.headers) #爬網(wǎng)頁(yè)圖片: requset=requests.post('http://tieba.baidu.com/p/4114581614',verify = False) r=r’src='http://www.lshqa.cn/bcjs/(http://imgsrc.baidu.com/.*?.jpg)'’#r=r’http://imgsrc.baidu.com/.+?.jpg’mylist=re.findall(r,str(requset.text))print (mylist)j=0for i in mylist: urllib.request.urlretrieve(i, 'C:/Users/Administrator/Desktop/img1/'+str(j)+'.jpg') j+=1
實(shí)例代碼擴(kuò)展:
# coding:utf-8import jsonfrom urlparse import parse_qsfrom wsgiref.simple_server import make_server # 定義函數(shù),參數(shù)是函數(shù)的兩個(gè)參數(shù),都是python本身定義的,默認(rèn)就行了。def application(environ, start_response): # 定義文件請(qǐng)求的類型和當(dāng)前請(qǐng)求成功的code start_response(’200 OK’, [(’Content-Type’, ’text/html’)]) # environ是當(dāng)前請(qǐng)求的所有數(shù)據(jù),包括Header和URL,body,這里只涉及到get # 獲取當(dāng)前get請(qǐng)求的所有數(shù)據(jù),返回是string類型 params = parse_qs(environ[’QUERY_STRING’]) # 獲取get中key為name的值 name = params.get(’name’, [’’])[0] no = params.get(’no’, [’’])[0] # 組成一個(gè)數(shù)組,數(shù)組中只有一個(gè)字典 dic = {’name’: name, ’no’: no} return [json.dumps(dic)] if __name__ == '__main__': port = 5088 httpd = make_server('0.0.0.0', port, application) print 'serving http on port {0}...'.format(str(port)) httpd.serve_forever()
到此這篇關(guān)于python調(diào)用api實(shí)例講解的文章就介紹到這了,更多相關(guān)python 如何調(diào)用api內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. vue-electron中修改表格內(nèi)容并修改樣式2. 利用FastReport傳遞圖片參數(shù)在報(bào)表上展示簽名信息的實(shí)現(xiàn)方法3. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式4. 微信小程序?qū)崿F(xiàn)商品分類頁(yè)過(guò)程結(jié)束5. 推薦一個(gè)好看Table表格的css樣式代碼詳解6. ASP常用日期格式化函數(shù) FormatDate()7. .NET 中配置從xml轉(zhuǎn)向json方法示例詳解8. ASP新手必備的基礎(chǔ)知識(shí)9. HTML中的XML數(shù)據(jù)島記錄編輯與添加10. 不使用XMLHttpRequest對(duì)象實(shí)現(xiàn)Ajax效果的方法小結(jié)
