一:發送請求
------POST--------
1、參數類型為:"Content-Type": "application/json",發送請求的時候,使用json來傳遞參數
response = requests.post(url=url,json=json)
2、參數類型為:Content-Type": "application/x-www-form-urlencoded,使用data來進行傳遞
response = requests.post(url=url,data=data)
3、檔案上傳接口的參數類型為:"Content-Type": "multipart/form-data;檔案應該使用files這個參數來進行傳遞
file = {"pic": ("bj01.png", open(r"C:\Users\MuSen\Desktop\page\image\ico.png", "rb"), "image/png")}
response = requests.post(url=url, files=file,data=data)
------GET-------
1、處理方式一:放到url位址後面
url = "http://httpbin.org/get?name=musen&age=18"
2、處理方式二:使用params來進行傳遞
url1 = "http://httpbin.org/get"
data = {
"name":"musen",
"age":18
}
response = requests.get(url=url1,params=data)
print(response.text)
二:列印傳回内容
1、text屬性:自動識别内容的編碼方式,有可能識别不準确出現亂碼
res1 = response.text
print(res1,type(res1)) ---string 類型
2、json方法:将字元串中的json類型資料轉換為對應的python值
使用json方法的前提:傳回資料必須是json格式的
res3 = response.json()
print(res3, type(res3)) ----dict類型
3、content屬性
res5 = response.content #傳回位元組形式的資料
res5 = response.content.decode("utf8") ---string 類型 #指定utf-8格式進行編碼,手動自動編碼方式,對頁面内容進行解碼
print(res5, type(res5))
提取傳回結果中的參數
import jsonpath
res = {'code': 0,
'msg': 'OK',
'data': {'id': 7800007,
'leave_amount': 0.0,
'mobile_phone': '18189098765',
'reg_name': '小檸檬',
'reg_time': '2020-03-21 09:49:27.0',
'type': 1,
'token_info': {'token_type': 'Bearer',
'expires_in': '2020-03-21 11:16:59',
'token': 'eyJhbGciOiJIUzUxMiJ9.eyJtZW1iZXJfaWQiOjc4MDAwMDcsImV4cCI6MTU4NDc2MDYxOX0.-zjbWEbXF9qdfvW1Wn0640HZnv3Xkdrx0nDedRTcsgk_URgU185yA-e2SjQUvVfsjA-FpJSKSOF4jjB-Jyv47A'}},
'data1': {'id': 7800007,
'leave_amount': 0.0,
'mobile_phone': '18189098765',
'reg_name': '小檸檬',
'reg_time': '2020-03-21 09:49:27.0',
'type': 1,
'token_info': {'token_type': 'Bearer',
'expires_in': '2020-03-21 11:16:59',
'token': 'eyJhbGciOiJIUzUxMiJ9.eyJtZW1iZXJfaWQiOjc4MDAwMDcsImV4cCI6MTU4NDc2MDYxOX0.-zjbWEbXF9qdfvW1Wn0640HZnv3Xkdrx0nDedRTcsgk_URgU185yA-e2SjQUvVfsjA-FpJSKSOF4jjB-Jyv47A'}},
}
# 使用字典的鍵值對 提取方式去提取
# # 提取使用者的id
member_id = res["data"]["id"]
print(member_id)
#
# # 提取token值
token = res["data"]["token_info"]["token"]
print(token)
# 使用jsonpath來提取
member_id = jsonpath.jsonpath(res, "$.data..id")[0]
print(member_id,type(member_id))
token = jsonpath.jsonpath(res, "$.data1..token")[0]
print(token)"""
. 代表直接子節點
.. 代表子孫節點(不管層級)
"""
拓展:
檔案下載下傳
res = requests.get(url="http://www.lemonban.com/images/upload/image/20190219/1550554131699.jpg")
print(res.content)
with open("lemon.png","wb") as f:
f.write(res.content)