咨詢熱線 400-001-5729

Python怎樣調(diào)用接口

發(fā)布時(shí)間:2022-02-12 10:32:15

Python培訓(xùn)

先上一個(gè)簡單示例:


  # -*- coding:utf-8 -*-__author__ = u'harry'

  import requests #先導(dǎo)入包,這是必須的url = 'http://XXXXXXXXXXXXXXX' #url:接口地址data = {'XXXX':'XXX'} #data:接口傳遞的參數(shù)headers = {'Connection':'close'} #header:傳遞header信息

  #files:接口中需要上傳文件則需要用到該參數(shù)r = requests.post(url,data = data,headers = headers) #請(qǐng)求url,獲得返回的數(shù)據(jù)信息print(r.text.encode('utf-8'))

  #獲得的返回?cái)?shù)據(jù)使用text方法進(jìn)行獲取,使用requets就是這么簡單。

  簡單的使用方法寫了,各位客官可以對(duì)其進(jìn)行很多的修改。比如說:封裝這塊代碼,每次可以進(jìn)行調(diào)用;可以添加循環(huán),變?yōu)樽詣?dòng)化,從excel中讀取數(shù)據(jù),然后進(jìn)行循環(huán)取值。 等等等等。。。。

  在最后再加上一個(gè)我封裝后的urllib庫 與 requests庫的對(duì)比代碼:

# -*- coding:utf-8 -*-__author__ = u'harry'import urllib.requestimport requests #先導(dǎo)入包,這是必須的import urllib.

parseurl = 'XXXXXXX' # url:接口地址data = {'XXX': 'XXX'} #data:接口傳遞的參數(shù)headers = {'Connection': 'close'} # header:傳遞header信息# files:接口中需要上傳文件則需要用到該參數(shù)def requests_test(url,data,headers):

response = requests.post(url,data = data,headers = headers) #請(qǐng)求url,獲得返回的數(shù)據(jù)信息

print(response.text,response.headers) #返回頭部信息def urllib_test(url,data):

data1 = urllib.parse.urlencode(data).encode('utf-8')

response = urllib.request.Request(url=url,data = data1)

html = urllib.request.urlopen(response)

print(html.read()) print(html.getcode(),html.msg) #獲得html返回的狀態(tài)

print(html.headers) #返回頭部信息#下面調(diào)用兩個(gè)方法:urllib_test(url,data)

requests_test(url,data,headers)

  關(guān)于這兩個(gè)庫的get請(qǐng)求,我就不多講了。

requests: requests.get("url")

  urllib:不傳入data就可以了。

  如果要解決接口返回值的unicode編碼,則html.read().decode('unicode-escape')

  不斷的學(xué)習(xí),不斷的攀爬,才能更上一層樓。


以上文章由長沙牛耳教育課程顧問整理編輯發(fā)布,部分文章來自網(wǎng)絡(luò)內(nèi)容真實(shí)性請(qǐng)自行核實(shí)或聯(lián)系我們,了解相關(guān)專業(yè)課程信息您可在線咨詢也可免費(fèi)申請(qǐng)?jiān)囌n。關(guān)注官方微信了解更多:150 3333 6050

免 費(fèi) 申 請(qǐng) 試 課